/ CSS Trick

Pure CSS Approach for Keeping Aspect Ratio

A problem of responsive development is to keep the aspect ratio of a container. For example, we don't want a video to be stretched when we resize the browser, or we want the cards keep their ratio so that the card layout won't mess up. Today I will introduce a pure CSS solution to tackle the issue.

Let's take embedding a youtube video as an example.

We will wrap the iframe with a container box, and add a class content to the iframe.

<div class="box">
  <iframe class="content" src="https://www.youtube.com/embed/pU9Q6oiQNd0" frameborder="0" allowfullscreen></iframe>
</div>

The box will be controlling the dimension of the content. Therefore, we will apply 100% width and height to the content and position it absolutely to the box.

.box {
  position: relative;
}

.content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

To adjust the box's height according to the width, we will use percentage padding to occupy the height instead of setting the height directly. The trick is based on the fact that percentage padding is calculated with respect to the width of the container.

.box {
  position: relative;
  padding-bottom: 56.25%;
}

Note that the 56.25% is calculated by this formula:

<aspect height>/<aspect width> x 100%

The padding bottom for 16:9 container would be 9/16 x 100%, which is 56.25%.

To consolidate everything, we have come up the following Codepen:

Read also...

  1. Maintain Aspect Ratio Mixin (for Sass)
  2. Fluid Width Video