Responsively maintain the aspect ratio of a container

This is a very handy tip for those who need to build a responsive block where the aspect ratio of an element within it maintains its aspect ratio: a background image or a video, for instance.

The trick is to put your content within two nested block elements, the outer one with relative positioning and bottom padding set as a percentage, and the inner one positioned absolutely to fill the space. The bottom padding is actually a measurement of the width of the element, so set it to 56.25% to get an aspect ratio of 16:9, to 75% for a 4:3 ratio.

That’s all well and good if you’re going to use a video but it works with images, even background images, you just need to know what the aspect ratio of the images you’ll be using are. Measure them in Photoshop or similar then pop along to this online aspect ratio tool to get the correct aspect ratio.

Anyway, here’s some example code:

The CSS:

div.wrapper {
  position: relative;

div.wrapper > div {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;

And the HTML:

<div class="wrapper">
    <div>CONTENT GOES HERE!</div>