CSS object-fit
- type
- property
- applies to
- <img>, <video>
- inherits
- no
- common values
- cover | contain | fill | none
Where it goes
On the <img> or <video> itself, with a width and height (or aspect-ratio) so there is a box to fit. Without a box of a different shape, object-fit has nothing to do.
Example
.avatar {
width: 64px;
height: 64px;
border-radius: 50%;
object-fit: cover;
}
.card img {
width: 100%;
aspect-ratio: 16 / 9;
object-fit: cover;
object-position: top;
}Common mistakes
- Setting width and height on a photo and shipping the squashed result. If the box is not the image's shape, you need object-fit: cover.
- Putting object-fit on the wrapper <div>. It only works on <img> and <video>. The wrapper needs overflow: hidden, and the img needs object-fit.
- Forgetting object-position when the crop cuts off faces. cover crops from the center by default. object-position: top keeps heads in portraits.