The CSS aspect-ratio Property

Want to control the proportions of your boxes in CSS?

Say hello to the aspect-ratio property.

What's the Big Deal?

The aspect-ratio property allows you to define the width-to-height ratio of an element. It's fantastic for ensuring your images, videos, and other boxes keep their proportions, no matter their size.

The Basics

Here's how it looks:

.box {
    aspect-ratio: 16 / 9;
}

That line will ensure our .box element keeps a 16:9 ratio. Think of it as the widescreen format for your favorite movies.

Why Use It?

Responsive Designs: Want a responsive box? Combine aspect-ratio with width or height, and let CSS figure out the rest!

No More Hacks: Those padding hacks for responsive YouTube embeds? Gone! Use aspect-ratio and simplify your life.

Flexibility: It plays well with Grid and Flexbox, so it's a great tool in your responsive toolkit.

How To Use It?

Here's a quick tutorial:

  1. Set the Ratio: Decide on your width-to-height ratio. Common examples could be 4:3, 16:9, 1:1 or anything in between.
.element {
    aspect-ratio: 4 / 3;
}
  1. Define a Dimension: Set either the width or height. The browser will calculate the other one for you!
.element {
    aspect-ratio: 4 / 3;
    width: 300px;  /* The browser will set the height! */
}

Here's an example you can go play with:

Watch Out! 🚩

Support: All modern browsers love aspect-ratio. But double-check compatibility for older versions. Check support here in case you have to support older versions.

Happy coding! 🙌

CSS
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.