CSS aspect-ratio

The new aspect-ratio feature in CSS lets you define the exact shape of a container without needing to declare both width and height. This is perfect for cases where the width or height is defined as a percentage, or where you’re using max-width or max-height, and want to keep the exact shape. Normally to keep the shape in this case, you would need to use Javascript and calculate the other dimension yourself to ensure it is correct. The new aspect-ratio feature in CSS now makes this much simpler, and removes the need for Javascript.

Usage

Using aspect-ratio in CSS is very straightforward. For example, to make a 150px x 150px square, you can create either of these divs:

<div style="width: 150px; aspect-ratio: 1"></div>
<div style="height: 150px; aspect-ratio: 1"></div>

You can also use it in scenarios where neither width nor height have been specifically defined (such as when using display: flex). But be careful in these cases, as the browser will try to maintain the aspect ratio at all costs, often resulting in the element overflowing its parent’s bounds.

Calculating aspect ratio

The value for aspect ratio is defined in the same way as screens and TVs, by dividing width by height. For example, a very common widescreen screen size is 1920 x 1080. The aspect ratio for this is 1920 / 1080 = 1.78.

To put it simply, if your element’s aspect ratio is less than 1, its height will be greater than its width. If your element’s aspect ratio is greater than 1, its width will be greater than its height.

Browser support

CSS aspect-ratio is currently supported in Chrome, with support likely coming for Firefox in the next few months. Take a look at CanIUse’s aspect-ratio page for detailed support info.

Demo

The demo below shows a container with a height of 150px. Click the buttons to change its aspect-ratio.

Your browser does not support CSS aspect-ratio. Please try the demo in another browser.

Choose an aspect ratio

height: 150px; aspect-ratio: 1;
Other recent posts: