Search code examples
htmlcssaspect-ratio

What does the CSS aspect-ratio property do that width declarations don't?


I was following a blog post about images optimization where the author said that it's a good practice to use the CSS property aspect-ratio giving the following example:

<img style="aspect-ratio: 5 / 3; width: 100%" ...>

I was playing around with Chrome and found out that if we declare the width of an image with some responsive width (let's say 100%), Chrome automatically does the math and picks up the correct aspect ratio for our image on the page. So, if the original image has sizes of 800x400, the browser automatically (implicitly) picks up the aspect ratio 2/1 and resizes the height of the image correctly when we shrink its width.

Why would I need to explicitly declare the aspect ratio in an example like the one above? Are there browsers that don't follow that approach of implicit calculating of the aspect ratio based on the source image? Did the author give a wrong example trying to explain that property? Or there's another benefit of doing that way?


Solution

  • The reason for declaring an aspect ratio for an <img> element, is to stop the page content from shifting when the image is finished downloading and inserted.

    The browser can only know the aspect-ratio for the image once it's done downloading, so giving browser an aspect-ratio "hint" will help the content on your page stop "jumping around" as things get loaded.

    Note: either declaring an aspect-ratio or declaring the width and height properties of the image will stop the content shift. It's just that using aspect-ratio allows the image to fit its containing element at the proper dimensions when used with width:100% (as can be seen in your example).