Aspect-ratio is so easy and so awesome

About a 3 minute read

Written by on

#css

Are you ever working on a website then stop and think, man CSS is cool. Well, that was my reaction the first time I used the aspect-ratio property. I mean, one property and you can set the aspect ratio of an element? That’s AWESOME!

The old way

Before this awesome property, you could still maintain an aspect ratio but you had to hack it a bit. The way you did it was by having a relative div with a padding-bottom as a percentage, 56.25% for 16 / 9, and then the child would have to be absolutely positioned. Usually you do this for videos or images, so it wasn’t too much of a pain for the child (iframe, video, img) to be absolutely positioned.

It looked something like this:

<div style="position: relative; padding-bottom: 56.25%">
    <iframe src="some-youtube-video-probs" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%"></iframe>
</div>

What about if you wanted a square?

<div class="position: relative: padding-bottom: 100%">
    <img src="probably-a-cat" alt="funny cat" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%" />
<div>

If you set up a global or helper class, it’s actually not too bad. The only pain area is the percentage value. You have to know what percentage equates to which aspect ratio.

The new way

So, the old way isn’t too bad, but when you see the new way it’s just so much better.

<iframe src="some-really-cool-video" style="aspect-ratio: 16 / 9"></iframe>

And the square:

<img src="probably-a-cat" alt="funny cat" style="aspect-ratio: 1 / 1" />

Boom. That’s it. Isn’t that amazing?

You don’t have to have a container div AND the value for the property is easily understandable. No more percentages. The value is the aspect ratio that you are wanting the element to display as. I swear, college me would’ve flipped for this.

In case you are curious, the tailwind class for 16 / 9 aspect ratio is aspect-video and a square is aspect-square.

It’s simple things like this that make me appreciate CSS.