Update (1/18): The example in this post is incorrect. I write about this in a follow up post.Disclaimer: This post does not define the actual implementation of the CSS aspect-ratio property. It is a reflection of my interpretation/expectation of how it would work based on my limited knowledge of the property at the time of writing this.
Over the weekend, there were a couple of tweets from @fantasai and @LeaVerou asking about expectations around the sizing of images when the aspect ratio defined does not match the dimensions defined on an image.
If you assigned a 200px by 100px JPEG an `aspect-ratio` of 1:1...— fantasai (@fantasai) January 15, 2021
... how would you expect the browser to size that out?
If you assigned a 200px by 100px JPEG an `aspect-ratio` of 1:1, what size would you expect the resulting image to be?— Lea Verou (@LeaVerou) January 16, 2021
I went over to the W3C working draft for Box Sizing Level 4 and read up a little on aspect ratios. While I'm consider myself well-versed in writing CSS, I'm not an expert on the details of the specs themselves. However, I interpret the question as follows:
The code might look something like this:
I think it would work like this:
There are two parts: the box that is represented by the <img> tag and the actual image represented by the src property of the tag.
I would expect that the actual image would render as 200x200, stretching it vertically because the aspect ratio is defined as 1:1 on the <img> tag. The 200px size is taken from the largest value between width/height.
The reason why I don't think it would render as 200x100 (respecting the height value) is because the default value for the
object-fit property is
fill. By changing the value for
object-fit, you can change the rendered size of the image within the 200x200 box. For example, setting
contain will render the image as 200x100 and vertically center it within the 200x200 (1:1) box.
There are a bunch of variables that you can toss into the equation to change the end result, but this is what I would expect to happen based on the use case asked by @fantasai and @LeaVerou.