object-fit

Robin Rendle on Updated on
##description##
Ad
`, } ); } })();

The object-fit property defines how an element responds to the height and width of its content box. It’s intended for images, videos and other embeddable media formats in conjunction with the object-position property. Used by itself, object-fit lets us crop an inline image by giving us fine-grained control over how it squishes and stretches inside its box.

object-fit can be set with one of these five values:

This is how we might set that property:

img {
  height: 120px;
}

.cover {
  width: 260px;
  object-fit: cover;
}
object-fit example

Because the second image has an aspect ratio that is different than the original image on the left it will stretch outside the realm of its content box, cropping the top and bottom parts of the image.

It’s worth noting that by default the image is centered within its content box but this can be altered with the object-position property.

Demo

The demo below shows five examples detailing how we might want an image to squish into a content box which is sometimes smaller or larger than its original width (resize the browser for a better idea of how this might work):

If the content of the image does not fill the content box for whatever reason then the unfilled space will show the element’s background, in this instance a light grey background.

Other resources

Browser support

It’s worth noting that iOS 8-9.3 and Safari 7-9.1 the object-fit property but not object-position.