PPK looks at aspect-ratio
, a CSS property for layout that, for the most part, does exactly what you would think it does. It’s getting more interesting as it’s behind a flag in Firefox and Safari now, so we’ll have universal support pretty darn soon. I liked how he called it a “weak declaration” which I’m fairly sure isn’t an official term but a good way to think about it.
This will produce a 16 / 9 element:
.movie-card {
aspect-ratio: 16 / 9;
}
This will too:
.movie-card {
width: 50%;
aspect-ratio: 16 / 9;
}
But this won’t:
.movie-card {
width: 150px;
height: 150px;
aspect-ratio: 16 / 9;
}
Because you’ve explicitly set the height
and width
, that is what will be respected. The aspect-ratio
is weak in that it will never override a dimension that is set in any other way.
And it’s not just height
and width
, it could be max-height
that takes effect, so maybe the element follows the aspect ratio sometimes, but will always respect a max-*
value and break the aspect ratio if it has to.
It’s so weak that not only can other CSS break the aspect ratio, but content inside the element can break it as well. For example, if you’ve got a ton of text inside an element where the height is only constrained by aspect-ratio
, it actually won’t be constrained; the content will expand the element.
I think this is all… good. It feels intuitive. It feels like good default behavior that prevents unwanted side effects. If you really need to force an aspect ratio on a box with content, the padding trick still works for that. This is just a much nicer syntax that replaces the safe ways of doing the padding trick.
PPK’s article gets into aspect-ratio
behavior in flexbox and grid, which definitely has some gotchas. For example, if you are doing align-content: stretch;
—that’s one of those things that can break an aspect ratio. Like he said: weak declaration.
It should probably be noted that
aspect-ratio
will still be respected in the event of too much text if you specifically declare how to handle it, like withoverflow-y: scroll
. See here for example https://codepen.io/jace-cotton/pen/mdWZqRaIn fact, if you really wanted to be forceful, you could
overflow-y: clip
it, and the text would just be cut off while the 16/9 aspect ratio would be maintained.Useful, thanks!
You can tell
aspect-ratio
to ignore the contents of the box by settingmin-height: 0
. It’s the initialauto
value that causes the height to respect its contents. (I think this would be worth incorporating into the article.)