aspect-ratio in CSS is very straightforward. For example, to make a 150px x 150px square, you can create either of these
<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.
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.
The demo below shows a container with a height of 150px. Click the buttons to change its
height: 150px; aspect-ratio: 1;