CSS object-fit
The object-fit property controls how an image or video fills its box when the box has a different shape than the media. Pick a value below to see it live, or type your own.
The object-fit property controls how an image or video fills its box when the box has a different shape than the media. Pick a value below to see it live, or type your own.
object-fit: fill | contain | cover | none | scale-down;
The example image above is tall (240×360) while its box is wide, so each value treats it very differently.
| Value | What it does |
|---|---|
fill | Stretches the image to the box size, distorting it (default) |
contain | Shows the whole image, scaled down to fit; empty space may remain |
cover | Fills the box completely, cropping whatever doesn't fit |
none | Keeps the original size; the box simply shows the middle part |
scale-down | Uses none or contain, whichever gives the smaller image |
With cover or none, part of the image is hidden. object-position chooses which part you keep, just like background-position:
.avatar {
width: 96px;
height: 96px;
object-fit: cover;
object-position: top; /* keep faces in view */
border-radius: 50%;
}
They do the same job for different things: background-size sizes a CSS background image, while object-fit sizes real <img> and <video> elements. Prefer real images for content that matters, because they get alt text, lazy loading and better SEO.
The image needs both a width and a height (or an aspect-ratio) different from its natural shape. If the box already matches the image, there is nothing to fit.
Yes, it works on video elements, and also on canvas, iframe and embed elements in modern browsers.
cover fills the whole box and crops the edges; contain shows the entire image and may leave empty bars.