object-fit
Decides how an image or video fills a box with different proportions.
- Initial value
fill- Inherited
- No
- Animatable
- no
- Applies to
- replaced elements, e.g. img, video, iframe
- JavaScript
element.style.objectFit = "cover"
Example
#.avatar {
width: 64px;
height: 64px;
border-radius: 50%;
object-fit: cover;
}<div style="display: flex; gap: 12px; align-items: center;">
<img class="avatar" src="/collections/covers/czy-warto-zostac-programista.webp" alt="" style="width: 64px; height: 64px; border-radius: 50%; object-fit: cover;">
<span>A landscape photo in a round avatar, without distortion</span>
</div>Definition and usage
#The object-fit property applies to replaced elements such as <img> and <video>. When you give them dimensions with different proportions from the file itself, by default the image is stretched and distorted (fill).
cover fills the whole box, cropping the excess, while contain fits the whole image, leaving empty strips. They are the equivalents of background-size: cover and contain, but for real images in HTML.
You choose the cropped part with the object-position property. By default the image is centred.
Syntax
#object-fit: fill | contain | cover | none | scale-down;Values
#- The image is stretched to the box, the proportions are distorted.
- The box is filled, the image edges are cropped.
- The whole image is visible, with empty strips above and below it.
- The image at its natural size, clipped to the box.
- The smaller of the none and contain options.
Values in practice
#fill
.demo { object-fit: fill; }cover
.demo { object-fit: cover; }contain
.demo { object-fit: contain; }none
.demo { object-fit: none; }scale-down
.demo { object-fit: scale-down; }Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Thumbnails in a grid look uniform thanks to a fixed box (e.g.
aspect-ratio: 1) andobject-fit: cover. - For logos
containis better, so no part of the mark gets cut off.
Related entries
#Practise it in lessons
#Spotted a mistake or missing an example? Write to us.