object-fit

Avatar of Robin Rendle
Robin Rendle on (Updated on )

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

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:

  • fill: this is the default value which stretches the image to fit the content box, regardless of its aspect-ratio.
  • contain: increases or decreases the size of the image to fill the box whilst preserving its aspect-ratio.
  • cover: the image will fill the height and width of its box, once again maintaining its aspect ratio but often cropping the image in the process.
  • none: image will ignore the height and width of the parent and retain its original size.
  • scale-down: the image will compare the difference between none and contain in order to find the smallest concrete object size.

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):

See the Pen object-fit by Robin Rendle (@robinrendle) on CodePen.

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.

Related properties

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.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

ChromeFirefoxIEEdgeSafari
3236No7910

Mobile / Tablet

Android ChromeAndroid FirefoxAndroidiOS Safari
1261274.4.3-4.4.410.0-10.2