Image Aspect Ratio – CSS Object Fit / object-fit

Hell Yes!

Displaying images in a container div while respecting aspect ratio has always felt cumbersome. But, it looks like all of the past solutions are now giving way to object-fit. I’d seen this tag in the but the lack of cross browser support made it unusable prior to the addition of support by Firefox 36 and Safari 8 (and the announcement that IE is being discontinued).

A quick intro.

Note *object-fit requires that the img tag or containing element be given a width and height.

object-fit values.

fill : stretches the image to the requested height / width.

contain : retains aspect ratio using max width or height to calculate the ratio for the other side.

cover : fills the box using max width or height, allowing overflow.

scale-down : uses none or contain defaulting to which ever displays the image first.

none : if the original image fits, it is displayed

Example CSS:

img {
    width: 300px;
    height: 300px;
    object-fit: contain;
}

Example on CodePen

Again, object-fit is not supported by IE, but a polyfill is available and IE is on it’s way out.

Read MDN Object fit for more concise info.

And check caniuse.com for up to date browser support.

Leave a Reply

Your email address will not be published. Required fields are marked *