Apply Aspect Ratio Sizing to Images with CSS object-fit

Share this video with your friends

Send Tweet
Published a year ago
Updated 2 weeks ago

The CSS property object-fit instructs an img to act as the container for its own contents. We can then use the value cover to have the image content behave similar to a background-image by scaling up or down to fit the provided dimensions. If the goal is for the image contents to remain fully visible within a container while maintaining its aspect ratio, we can use the value scale-down.

Stephanie Eckles: [0:00] Here we have three standard cards. What happens if we try to add an image? Adding a native image tag results in unevenly sized images. A common solution is to bring the image in as a background instead, but modern CSS gives us a new property called object-fit.

[0:19] For each of our card images, we will apply the property object-fit: cover. On save, we do not yet see a difference, because we need to apply specific dimensions for the image to fit within. The first improvement is width: 100%. Now, the images do not grow larger than the card container.

[0:41] The second dimension to add is height. For that, we'll use the value 25 view height. On save, you can see how each image has been scaled either up or down to fill the dimensions we have set. object-fit: cover results in the image behaving much like a background image with the advantage of retaining the semantics offered by the image tag.

[1:05] Another common scenario that object-fit can provide solution for is the desire to scale unevenly sized images within their containers without losing their aspect ratio, but ensuring the whole image is viewable.

[1:18] For this scenario, we'll use object-fit with the value of scale-down. Once again, to see an impact, we also need to provide width: 100% and again we'll provide a height of 25 view heights. The results of using object-fit with height and width defined is that the image will become the container for its own contents.

[1:41] As you can see, the image tag fills the dimensions that we provided, but the contents itself have been scaled down to fit within those dimensions while keeping its aspect ratio. For this example, the usage of the scale-down value means that either none or another property contained will be chosen whichever results needs smaller concrete object size.

[2:06] Because the use of object-fit causes the image to act like its own container, we can also add value such as padding, which as a normal block container, results in space around the image contents.

[2:20] In summary, object-fit results in an image acting as its own container where the value cover mimics the behavior you would expect from a background image and instructs the image contents to expand or fill the dimensions. Scale-down results in the image contents retaining their aspect ratio but scaling within the dimensions set on the image.