Signup/Sign In
LAST UPDATED: APRIL 21, 2021

CSS object-fit

The CSS object-fit property specifies how an element should be resized to fit in its container element. It is specially used for images, videos, and other embedded media formats. The purpose of this property is to fill the parent container either by stretching or shrinking the element inside it irrespective of its aspect ratio.

Example of Object-fit property in CSS

In the given example, we have set the height and width of the image on their own. However, we can see that the image is being stretched to fit in the container of 250px * 350 px, and its original aspect ratio is destroyed.

<!DOCTYPE html>
<html>
<head>
  <title>CSS Object-fit</title>
  <style>
    img {
      width:250px;
      height:350px;
     
    }
  </style>
</head>
<body>
  <img src="studytonight.png" alt="studytonight" width="400" height="300">
</body>
</html>

Output:

Values of CSS object-fit

The object-fit property has five different values. these are given below:

S.No. Value Description
1. Fill The fill is the default value that allows the element to fill the content box. If the actual ratio of the element does not match the actual ratio of the box then the element will either stretch or shrink itself to get fit in the box.
2. contain The contain value increase or decrease the size of the element to fill the container and also preserves its aspect ratio.
3. cover The cover value is used to maintain the aspect ratio of the element while filling the element's entire content box. If the aspect ratio of the element does not match the aspect ratio of its container, then the element will be clipped to get fit in the box.
4. none The none value does not resize the element to get fit in the container box. The element remains at its original size and ignores the height and width of the parent element.
5. scale-down The element is sized as if none or contain were specified, which will result in the smallest concrete object size.

Example: Applying all values of object-fit in CSS

In the given example, we have demonstrated all the possible values of the object-fit property:

Conclusion

In this article, we have learned how to make an element to be fit in its container element. This can be done using object-fit property and by using its various value you can adjust the element within its parent element according to you.



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight