object-fit: A Starter Guide
Dom Jay
October 20, 2021
import InlineCalloutCluster from '../../components/InlineCalloutCluster.astro';
import InlineCallout from '../../components/InlineCallout.astro';
Let's get into it
By using the object-fit property, we can define how an element responds to its parent containers height and width. This property is mainly used alongside images and videos, and can let us have further control over how it allows an inline image to be displayed.
Looking at the example above, the inline image can be adjusted to the size of it's parent container - try resizing the window - it will always fit the box. There are a number of values that can be used to set .
What values can be used?
There are 5 values that can be used for this property; , , , and .
Fill
Similar to background-size, the content is sized to completely fill the content box of the element, regardless of the height and width. If the aspect ratio of the content does not match the aspect ratio of the element, then it will stretch to fit. The image below is horrifically stretched to really show this style.
Contain
When using , the content scales to keep its aspect ratio while also fitting within the boundaries of the elements content box. Using this can make the object display gaps vertically or horizontally.
The entire object is made to fill the box, while preserving its aspect ratio, so the object will be "letterboxed" if its aspect ratio does not match the aspect ratio of the box.
Cover
This is using , which is what we are using at the top of this post, however, it will not "letterbox" the object to keep it's aspect ratio. Instead it will continue to expand the content to fit the content box, often cropping the content as a result.
Scale-Down
chooses the smallest object size between the results of and being used.
None
For , the width and height of the content box is ignored by the object, which will maintain it's original size.
Practical Examples
Responsive Images with Picture Element
works particularly well with the element for responsive images:
Working with Different Aspect Ratios
Here's how handles different aspect ratios:
See the Pen
Object-Fit Example #1 by Dom Jay (@dominickjay217)
on CodePen.
Performance Considerations
When using with large images, consider these tips:
Always specify both and attributes on your images to prevent layout shifts
Use appropriate image formats and compression
Consider using for images below the fold
Use and attributes for responsive images
Support?
Support is excellent across all modern browsers. Since IE11 has been officially retired by Microsoft, you can safely use without any fallbacks.
So, what are you waiting for? Go try it out!
Discussion in the ATmosphere