Aspect-ratio in CSS

Aspect-ratio in CSS

ยท

3 min read

This is a short article about aspect-ratio property in CSS. While reading about aspect-ratio I found that this will be a very helpful property in making a website responsive. So in this article we will basically talk about responsiveness using aspect-ratio.

Let's first understand what aspect-ratio is

This is a very basic term we often use while talking about mobile phones. The aspect-ratio of an element describes the proportional relationship between its width and height or we can say that it represents the width-to-height aspect-ratio of the viewport.

The two most commonly and standard aspect-ratio are 16:9 and 4:3. Aspect-ratio is a range feature so we can use the prefixed min-aspect-ratio and max-aspect-ratio variants.

So as I said it is very helpful in making a website responsive let's understand it better with an example.

<body>

</body>
body {
    width: 100vw;
    height: 100vh;
    background: blue;
}

So as you can see in the above code we gave body height and weight equal to that of viewport and gave it red color.

Now making it responsive

body {
  width: 100vw;
  height: 100vh;
  background: red;
}
@media (max-aspect-ratio: 1/1) {
  body {
    background: #ef476f;
  }
}
@media (max-aspect-ratio: 16/9) {
  body {
    background: #ffd166;
  }
}
@media (max-aspect-ratio: 4/3) {
  body {
    background: #06d6a0;
  }
}
@media (max-aspect-ratio: 3/2) {
  body {
    background: #118ab2;
  }
}
@media (max-aspect-ratio: 8/5) {
  body {
    background: #073b4c;
  }
}

So now you can see we have applied different aspect-ratio to make it responsive and in every aspect-ratio we have applied different colors so that you can see the changes easily.

I used it only with color property to keep it simple. You can try out it with any CSS property.

Alt Text

Here in the above image you can see color varies as the viewport ratio varies.

If you are reading on a PC you can check it by resizing the window or you can try it on different responsiveness checking websites, just copy the below link and paste there in the following responsiveness checking websites:-

Copy this link ๐Ÿ‘‡

cdpn.io/ritvikbunny/debug/QWEVxLW/yPAJjRPGZ..

Paste above link in following websites ๐Ÿ‘‡

Responsive Test Tool

Website Planet

Am I responsive

Cover:- Rajat Gour

Thank you for reading.

Please feel free to share your views about it.

I hope you liked it and found it helpful.

Connect with me on Twitter or LinkedIn

My personal blog blog.ritvikdubey.com