Responsive aspect ratio with CSS

Have you ever had to match a design that has some perfectly square element in it? Let's call those element boxes. Maybe these boxes contain an image, and so you go "ah, that's fine, the image will dictate the size". Well, maybe not.

The thing is, maybe the provided image will not always be a perfect square, specially if you intend to work with user-generated content. Or maybe the image should act as a background, or maybe there is no image at all.

How do you make an element perfectly square, at all screen sizes?

With some padding.

How is padding calculated?

Padding in CSS is calculated based on the width of the element's parent.

Say you have a .container element, with a .box element inside and the following styling:

.container {
  width: 400px;

.box {
  background-color: tomato;
  width: 200px;
  padding-bottom: 100%;

The .container element is 400px wide.
The .box is 200px wide and 400px tall, because, in this case padding-bottom: 100% = 400px.

Here's a preview:

See the Pen Box width based on padding by David (@dapd007) on CodePen.

But maybe you don't want a container, neither do I.
We can use a pseudo-element to apply the padding:

See the Pen Responsive box with pseudo-element by David (@dapd007) on CodePen.

Remember to add the content and display attributes to the ::after pseudo-element, otherwise, it will not show.

Also, keep in mind that whatever content you are adding to the box, it has to be absolute positioned, and you should try to keep it short.

Aspect ratios

Ok, we have a perfect square (ratio 1:1), but what if we want something with a 16:9 aspect ratio? Like an embedded video, for instance.

Well, we know that the padding is calculated based on the width of the element's parent.
With that in mind, we just need to make a simple calculation: divide the height by the width, and multiply that by 100 to get the padding percentage.

For instance, to achieve a 16:9 aspect ratio:

9 / 16 = 0.5625, 0.5625 * 100 = 56.25, so we need a padding with a value of 56.25%.

Here are some more examples:

See the Pen Responsive aspect ratios by David (@dapd007) on CodePen.

Dynamic width

Since the padding is always calculated from the element's width, this trick also works with non-fixed widths (eg. 50%, 100%).

So no matter how wide the element is, it will keep its aspect ratio across multiple screens sizes.

If you have any questions feel free to ask them in the comments below.

Until the next one, peace!