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 :
CSS rules without object-fit (similar to object-fit:fill
)
img {
width: 320px;
height: 320px;
/* object-fit: fill; */
}
Result :
CSS rules with object-fit: cover
img {
width: 320px;
height: 320px;
object-fit: cover;
}
Result :
CSS rules with object-fit: contain
img {
width: 320px;
height: 320px;
object-fit: contain;
background-color: #808080;
}
Result :
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 propertybackground-image
. (I will show later how to do this).
Thank you for passing by and reading this tutorial.
Check out my personal blog to see more.