What Are Aspect Ratio Boxes?
Raymond Lo • October 04, 2022
3 min read
Have you ever come across an image on the web and it appears cut off? Chances are, it's an element with a background image that doesn't have the same aspect ratio as itself, or even worse an unresponsive image! If it's the former, aspect ratio boxes could be a possible solution to this problem. Aspect ratio boxes are elements that preserve their aspect ratio even when its width changes.
The video compares two elements that have a background image set with CSS. The first element uses the aspect ratio box technique whereas the second does not. Initially both images render nicely, but as we resize the screen the second image becomes cut off. This makes designing responsively a nightmare.
Some may notice that the second image may be cutoff because of a fixed height property set on itself or a parent up the tree. However, if the height was not fixed and set relative to the screen width; to fill the full width of the device without repeating the background image would cause the image to be distorted and "stretched". Aspect ratio boxes solve both of these problems.
This is the Codepen for the video above. Play around with it!
How Do They Work?
We can create these fixed aspect ratio boxes because the vertical padding percentage of an element is based on the width of its parent.
The cat image above is served to us as 400x262. What we don't want to do here is set tens of media queries for various screen sizes to adjust for the image being cut off or blurred. Instead we should create an aspect ratio box with the same aspect ratio (262:400) for the image. Let's do just that!
First, we should apply height: 0
and remove any borders to our box as it will affect the dimensions of our box and give us an unwanted aspect ratio. Next we decide our vertical padding percentage, padding-bottom
or padding-top
will both work. Now because our vertical padding is a percentage and is also relative to the width of the parent element; our element will always have a height that will give us the same aspect ratio. In our case, we take the height (262px), divide it by the width (400px) and multiply it by 100 which gives us 65.5%.
Padding-bottom (%) | Parent Width (px) | Height from Padding-bottom (px) | Aspect-ratio of element |
---|---|---|---|
65.5 | 600 | 393 | 393:600 = 131:200 |
65.5 | 750 | 491.25 | 491.25:750 = 131:200 |
65.5 | 900 | 589.5 | 589.5:900 = 131:200 |
What Lies Ahead?
This trick has been around for a while, but there's a modern CSS property that addresses this and makes it much more intuitive. The property name is aspect-ratio
and you can check its browser compatibility.