object-fit

Term side of the Card.
Topic: Image Handling
Unit title: object-fit
Categories: Property
Explanation side of the Card

Explanation: The property that specifies how an element's content should fit within its container. It works with replaced elements like images and videos, enabling to set the content to 'contain', 'cover', 'fill', 'scale-down' or 'none', adjusting how it scales and fits.

Browser compatibility:
  • The chrome browser supports this feature starting from version 32.
  • The edge browser supports this feature starting from version 79.
  • The firefox browser supports this feature starting from version 36.
  • The safari browser supports this feature starting from version 10.
Availability: 

Example

Wrongcss
.card img {
  width: 100%;
  height: 200px;
}
Rightcss
.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 width is set and object-fit has nothing to fit into.
  • Using object-fit on a div with a background image and nothing changes.

Key points

  • Images with object-fit have both a width and a height set.
  • Cropped images use object-fit: cover; images that must be fully visible use contain.
  • Background images use background-size, since object-fit only works on replaced elements like img and video.

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.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy