Aspect ratio boxes

Sometimes you need to size an HTML element without knowing it’s precise size.

So you might know it needs to be 16:9 – a common ratio for images and videos – but not exactly how wide the element will be on the page.

That means you can’t determine the height either, since it’s calculated from the height.

We can get CSS to calculate it for us, even if we don’t know the width.

Here's the HTML code.

<div class="ratio-outer">
	<div class="ratio-inner">
		Aspect ratio box
	</div>
</div>

And here’s the CSS.

.ratio-outer {
	height: 0;
	overflow: hidden;
	padding-top: 56.25%;
	position: relative;
}
.ratio-inner {
	position: absolute;
	top: 0;
	right: 0;
	bottom: 0
	left: 0;
}

But that’s just for 16:9. How can we calculate the padding-top value for other ratios?

So you’ve probably worked out how it works. The padding-top value is a percentage of the width, but it’s applied to the height.

The value we’ve used in padding-top is calculated to render the element at the correct size.

The formaular is (height / width) * 100.

Common aspect ratios are:

RatioPercentage
5:360%
4:375%
16:956.25%
3:266.66%

Here’s a free tool I’ve made to help you calculate your padding-top percentages.

Share