The CSS property object-fit scales an element to within the width and height of the container it’s in. Background images are the most common element that you will come across as a developer that uses this property.
There are five possible values for the object-fit property. We’ll use an image as the example for illustrating the different values:
- object-fit: contain – With contain, the aspect ratio of the element that goes in the container (image in this instance) is maintained. If the ratio does not match, you will see bars (think of when widescreen videos were released and on older televisions you would see bars on the top and bottom of the screen) on whichever sides the ratio does not match.
- object-fit: cover – Cover maintains the aspect ratio while filling the content box. If the aspect ratio doesn’t match, the image will be clipped to fit.
- object-fit: fill – The image will be sized in this instance to fill the element’s content box, regardless if the original aspect ratio matches or not. This will probably stretch the image to fit.
- object-fit: none – The image will maintain its original size.
- object-fit: scale-down – The scale-down property automatically chooses either none or contain, whichever results in a smaller overall image size. In this instance, scale-down will choose contain:
Browser support is pretty widespread for this property. Double check the support if you are developing for older Internet Explorer, Microsoft Edge or Opera browsers.
Conclusion
In this article, we took a look at the object-fit property. It’s used on elements that can be inserted and fill a container. The property is directly used on an <img> or other replaced elements to control how the <img> fills the container. Use the object-fit property in conjunction with the object-position property to control how the element is displayed in its container.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.