object-fit

Sets whether images and videos are stretched, letterboxed, or cropped to fit their box. Images you used to crop as backgrounds with background-size can stay as img elements.

Modern approach

Keep the image as an <img> and crop it to fill the box. When cropping around the center, you don’t need to set the position either.

.thumbnail {
  width: 200px;
  height: 200px;
  object-fit: cover;
}
<img class="thumbnail" src="photo.jpg" alt="Product photo" />

Legacy approach

The image was set as a background and cropped with background-size: cover. Since the HTML became a div instead of an image, adding alternative text required role="img" and aria-label.

.thumbnail {
  width: 200px;
  height: 200px;
  background-size: cover;
  background-position: center;
}
<div
  class="thumbnail"
  role="img"
  aria-label="Product photo"
  style="background-image: url(photo.jpg)"
></div>

Things to watch when replacing

  • object-fit only works on replaced elements such as <img> and <video>. Rewrite background images on a div as <img>.
  • The initial value of object-position is the center (50% 50%). The initial value of background-position is the top left (0% 0%), so if the legacy approach set center, you can drop it after replacing. To crop around a point other than the center, set it with object-position.
  • It only has a visible effect when the box’s aspect ratio differs from the image’s. Set both the width and the height of the box, or set its ratio with aspect-ratio.
  • Going back to <img> lets you use alt, loading="lazy", and srcset as they are.

Browser Support

  • Chrome

    v32+
    2014-01-14
  • Edge

    v79+
    2020-01-15
  • Safari

    v10+
    2016-09-20
  • Safari (iOS)

    v10+
    2016-09-13
  • Firefox

    v36+
    2015-02-24

Search by feature name or code

e.g. aspect-ratio, :has(), padding-top

Try a different word or a property name.

Could not load search.