Responsive / fluid width videos

How I’ve done responsive videos in the past

In the past I’ve used a couple of different methods to achieve responsive videos:

At the end of the day both of these methods are achieving the same thing using similar HTML and CSS. The major difference between is how they add the HTML to the page. FitVids injects the HTML and CSS into the page using Javascript, while Bootstrap requires you to manually add the embed wrapper to each video (this can also be automated in most content management systems).

The HTML

The HTML for both is pretty straightforward you have wrapper div and an iframe. In bootstrap the iframe would need a class added to it while FitVids handled this.

<div class="wrapper">
  <iframe src="..."></iframe>
</div>

The CSS

As with the HTML the CSS between the two is very similar.

First you have the wrapper class

.wrapper {
  width: 100%;
  display: block;
  position: relative;
  overflow: hidden;
  padding: 0;
}

The iframe styles

iframe {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
}

Setting the aspect ratio

This is where the real magic of it happens. You would set either the top padding of the wrapper (FitVids) or a psuedo selector of the parent (Bootstrap) to a value relating to the aspect ratio of the video. For this example I’m going to use a value of 56.25%, since the video is 16x9 (to learn how to find this value you can read this A list apart article by Thierry Koblentz).

.wrapper::before {
  content: "";
  display: block;
  padding-top: 56.25%;
}

How I manage responsive videos now

Today we have the CSS properties aspect-ratio and object-fit that make this much simpler to manage.

HTML

The HTML can be pretty simple. I’d suggest adding a class to iframes that you want to be responsive (I’d probably avoid globally adding it to all iframes, just incase there are embeds you don’t want working this way).

<iframe class="responsive-video" src="..."></iframe>

CSS

The CSS in this method is quite a bit more clear.

.responsive-video {
  width: 100%;
  height: 100%;

  aspect-ratio: 16 / 9;
  object-fit: contain;
}

Working example

Additional improvements

Not all videos will be 16:9 so you could add some additional class to cover more aspect ratios.

.responsive-video {
  width: 100%;
  height: 100%;

  aspect-ratio: 16 / 9;
  object-fit: contain;
}

.responsive-video--4x3 {
  aspect-ratio: 4 / 3;
}

.responsive-video--1x1 {
  aspect-ratio: 1 / 1;
}