Back to Blogs
Image For Blog

CSS rule aspect-ratio now works in all major browsers

Coding

18 Nov 2021

The CSS rule aspect-ratio is now working in all major browsers. Around 77% adoption according to caniuse.com which isn't bad going really.

Flexbox gap was recently added to major browsers (funnily enough safari actually adopted this before chrome! Unbelievable) and is a god send in itself. Now this has been rolled out were soon hopefully getting some container queries and we will very well be in the next stage of CSS.

If you're wondering what in the f*** is aspect-ratio?? Well let me tell you...

It has been a nightmare to get images to retain their natural aspect ratio which usually can be done with a bit of hacky padding styles. Now we can choose the aspect ratio straight off with this new rule.

So? How do I use this new fancy css rule?

The ratio is specified with a width/height. If you dont put in a height it will default to 1. So some examples of use where you may want to keep the ratio of the image true but change the size.

aspect-ratio: 1 / 1;
aspect-ratio: 16 / 9;
aspect-ratio: 0.5;

As usual the only browser that doesn't like this is Internet Explorer, so you will have to still have a fallback for this using the padding hack unfortunately.

The fall back is easy enough to implement using the @supports at-rule. Here is an example of an implementation.

div { padding-top: 50% }
@supports(aspect-ratio: 1/1) {
div {
padding-top: 0;
aspect-ratio: 16/9
}
}

I hope this helps you in the coding world. I know it's helping me a hell of a lot to get away from spaghetti css hacks!

This website was built in SVG animation and CSS3 Animation.

This is an ongoing project to better understand SVG animation across browsers so this website may change often.

For the best experience use Chrome on desktop.