CSS for Cropping Images

April 19, 2017, 10:24 a.m.

I've been struggling with how to display images of various sizes in the same size. You can adjust the height and width of the image, or the max-height and max-width, but those will skew the aspect ratio.

To date, I'd been addressing this by putting the image in a sized div, and hiding the image that was outside the div, but this causes issues with positioning - you have to position the image the way you want it in the div - so the image is always cropped on top or on bottom, and not centered.

I just found a simple CSS solution to this:

img {
    object-fit: cover;
}

This will center and crop the image to a size specified by the image tag. 

Labels: coding , css

No comments

Archives