How to Use CSS aspect-ratio — SitePoint


There are times when we really need to maintain a specific ratio between the width and height of responsive elements on a web page. This has been possible for a long time via various CSS tricks. The CSS aspect-ratio property is a game changer, meaning we can now specify the aspect ratio of an element in a single line of code. Let’s look at how to use aspect-ratio.

Table of Contents
  1. Examples of Where Aspect Ratio is Important
  2. Responsive YouTube Videos
  3. A Responsive Image Gallery
  4. Maintaining Consistent Avatar Sizes with aspect-ratio
  5. Useful Things to Know about aspect-ratio
  6. Conclusion

Examples of Where Aspect Ratio is Important

By its nature, the Web is a fluid medium, and it’s usually better to allow elements on a web page to be as fluid and flexible as possible.

However, there sometimes are reasons to set limitations on the size of elements. For example, we might want to maintain the width-to-height ratio of certain elements — such as responsive YouTube videos, items in an image gallery, or rounded avatars.

Let’s first look at three practical uses of aspect-ratio, and then cover some useful things to know about how it works.

Responsive YouTube Videos

If you’ve ever embedded a YouTube video in a web page, you’ll know that the embed code comes as an