CSS: How to preserve aspect ratio for an HTML element

The Problem: How to set aspect ratio for a HTML element

In my case I needed that for a slider. But sometimes it can be required by some fancy layout or gallery component.

The Solution:

It’s simpler than you think! Lets assume we want to preserve 4:3 aspect ratio for slide placeholder to display an image. We cannot use fixed value, because our image will scale on smaller screens.

Lets do some math. Aspect ratio of 4:3 means that the height is equal to 3/4 of the width.
So to calculate percentage value we need to multiply 3/4 by 100% – which is 75%. Now we can write our CSS code:

div {
  width: 100%;
  padding-bottom: 75%;

The only tricky part is placing the content inside these elements. We need to use absolute positioning (see examples below).
More about aligning content you can find here.

Let me calculate some popular aspect ratio values for you. Just use it as bottom padding value:

aspect ratio percentage value
16:9 56.25%
4:3 75.00%
3:2 66.66%
36:10 27.77%
2:1 50.00%


See this code pen.