object-fit
Example
.card img {
width: 100%;
height: 200px;
}.card img {
width: 100%;
height: 200px;
object-fit: cover;
}object-fit: cover crops the image to fill the box instead of stretching it to the new proportions.
Common mistakes
- The image is stretched because only
widthis set andobject-fithas nothing to fit into. - Using
object-fiton adivwith a background image and nothing changes.
Key points
- Images with
object-fithave both awidthand aheightset. - Cropped images use
object-fit: cover; images that must be fully visible usecontain. - Background images use
background-size, sinceobject-fitonly works on replaced elements likeimgandvideo.
Interview questions
What is the difference between object-fit cover and contain?
cover fills the whole box and crops the overflow. contain shows the whole image and leaves empty space.
Does object-fit work on background images?
No. It works on replaced elements like img and video; for backgrounds use background-size: cover.