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-fitonly works on replaced elements such as<img>and<video>. Rewrite background images on adivas<img>.- The initial value of
object-positionis the center (50% 50%). The initial value ofbackground-positionis the top left (0% 0%), so if the legacy approach setcenter, you can drop it after replacing. To crop around a point other than the center, set it withobject-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 usealt,loading="lazy", andsrcsetas they are.
Browser Support
Chrome
v32+2014-01-14Edge
v79+2020-01-15Safari
v10+2016-09-20Safari (iOS)
v10+2016-09-13Firefox
v36+2015-02-24