Day 42: aspect-ratio

posted on

It’s time to get me up to speed with modern CSS. There’s so much new in CSS that I know too little about. To change that I’ve started #100DaysOfMoreOrLessModernCSS. Why more or less modern CSS? Because some topics will be about cutting-edge features, while other stuff has been around for quite a while already, but I just have little to no experience with it.


Yes, I know, aspect-ratio is not the hottest shit, but Safari only starting supporting it in version 15 and there’s a lot I didn’t know about the property. That’s reason enough for me to write about it. :)

Defining ratios

You can use the aspect-ratio property to define the preferred aspect ratio for a box by defining a preferred width and height.

The maximum width of the following element is 400px, and due to the defined ratio of 16 / 9 the height equals 225px (400 / 16 * 9) = 225). If the available width gets below 400, the height scales accordingly.

div {
  aspect-ratio: 16 / 9; /* aspect-ratio: width / height */
  max-width: 400px;
}

Instead of writing aspect-ratio: 16 / 9 we can also write aspect-ratio: 400 / 225.

div {
  aspect-ratio: 400 / 225;
  max-width: 400px;
}

Squares

If you want to create a square, you need a ratio of 1:1, or 42:42, or 742617000027:742617000027;

div {
  aspect-ratio: 1 / 1;
  max-width: 400px;
}

That's the same as writing aspect-ratio: 1 because if you omit the second value, the value for the height is 1 by default.

div {
  aspect-ratio: 1;
  max-width: 400px;
}

Single value ratios

If aspect-ratio: 1 equals aspect-ratio: 1 / 1, this means that aspect-ratio: 4 equals aspect-ratio: 4 / 1.

div {
  aspect-ratio: 4;
  max-width: 400px;
}

width, height, and aspect-ratio

aspect-ratio has no effect if you set the value of both the width and height to something other than auto.

div {
  aspect-ratio: 16 / 9;
  width: 250px;
  height: 250px;
}

preferred, not enforced ratio

If the content of your box is larger than the preferred height, content won't be cut-off but the box grows with its content, ignoring the ratio.

div {
  aspect-ratio: 4;
  max-width: 400px;
}
  • A
  • B
  • C
  • D
  • E
  • F

You can change the behaviour by defining a different value for the overflow property.

div {
  aspect-ratio: 4;
  max-width: 400px;
  overflow: auto;
}
  • A
  • B
  • C
  • D
  • E
  • F

See on CodePen

Further reading

Do you want to learn even more awesome CSS?

I'm running a workshop with my friends at Smashing Magazine in which I introduce you to the most useful modern features in CSS and show how you can implement them today in your code base to improve scalability, maintainability, and productivity.

Learn more about the workshop!

Overview: 100 Days Of More Or Less Modern CSS