CSS3 object-fit, to make ratio friendly image inside container
If you ever had a chance to work with an image to be fit inside a container different ratio that of the image, then this "object-fit" property must not be new to you. Recently I was in a situation like this, and I tried all possible ways which I was known (i.e hidden overflow, scale, etc.,.) and I ain't got exact result as I wanted. Later I found this lifesaver property which taken care of what I exactly wanted, in a single piece of a line!
Let us consider a square container (i.e 1:1 ratio)
Inside which we wanted to place an image with different ratio that of the container. Let us assume that the image is of dimension 600x900
It overflows the container and it adds scroll-bar to the page. Hence we hide overflow from the container.
Though overflow is taken care now, it's size exceeds the container. So we control it by giving exact size of the container.
Now it occurs stretching of the image to fixed dimensions and it fails. And another experiment with 100% width and center aligned text container.
In the first case, though we attained our required ratio the images stretches and in the second case, though we controlled stretching of the image, it loses its ratio. In either case, we ain't attained our result. Here comes object-fit property into the play.
(selector) {
/*possible values*/
object-fit: fill | contain | cover | none | scale-down;
}
And now ratio and dimensions, both are taken care in a single line. By default, the image will be positioned center, to alter the position of image object-position property is used.
In object-position, the first part denotes horizontal position and later changes vertical position.
Conclusion:
It’s worth noting that iOS8+ supports the object-fit property but not object-position.
Engineering Leader | Building Scalable, High-Quality Software Solutions | Empower Teams | Frontend community lead @ ThoughtWorks India | Micro Frontend | Design Systems
5 年good one. similar options available when we use the image as a background (using background-size property).