CSS object-fit : adjustimage content

CSS Tutorials

The object-fit property adjusts the content to the box size of the element. It is practically useful to scale automatically the content of image and video tags.

CSS object-fit : adjustimage content

The object-fit property adjusts the content to the box size of the element. It is practically useful to scale automatically the content of image and video tags.

How to use this property?

It can take one of the following value:

object-fit: fill | contain | cover | none | scale-down;  

Here are few examples:

Here is the HTML code of the image element :

<img src="img-sample-16-9.jpg" alt="...">

And this is the original image :

image default

CSS rules without object-fit (similar to object-fit:fill)

img {
  width: 320px;
  height: 320px;
  /* object-fit: fill; */
}

Result :

object fit fill or unset

CSS rules with object-fit: cover

img {
  width: 320px;
  height: 320px;
  object-fit: cover;
}

Result :

object fit cover

CSS rules with object-fit: contain

img {
  width: 320px;
  height: 320px;
  object-fit: contain;
  background-color: #808080;
}

Result :

object fit contain

Use cases

There are many reason why you may need this property. Personally, I use it often:

  • To auto-scale image or video content of an img tag (or a video tag) with fixed height and width.
  • To keep the aspect of images displayed in a grid view. This allows you to have the same aspect ratio for the images of the grid without deforming their appearance.
  • To set a background image or video: An image or a video set as fixed or absolute position with object-fit: cover can be used as an alternative to the CSS property background-image. (I will show later how to do this).