CSS aspect ratio and some everyday uses for it
CSS aspect-ratio has been working in browser for a couple of years now and I want to share some ways that I frequently utilize it in my day to day work.
2022 new CSS hotness series
This is article is a part of a series I'm going to be doing talking about some of the cool new things that have come to CSS in the last couple of years.
I most often find myself reaching for aspect-ratio to size images in combination with object-fit. It can be useful to keep images sized similarly between different items in a grid of content (at least until subgrid works everywhere).
Example of a figure/caption
In this example I have a figure and caption. The figure is using a grid layout that limits the width of the image and then the image has an aspect-ratio of 1 which will keep is square.
Another frequent use I find for aspect-ratio is to make videos embeds (specifically iframes from viemo/youtube) responsive. This requires fairly minimal CSS. You need to set the width and height to 100%, then set the aspect-ratio to match the video (in this case 16 by 9), and then
object-fit: contain, this will keep the image the correct ratio and allow it to resize.
aspect-ratio: 16 / 9;
Example of a responsive video
I've got a longer post on just responsive videos and some history on how they used to be done.