Making Embedded Videos Responsive

By Cory LaViska on June 26, 2019

Video hosting is hard to get right. It's almost always better to use a third-party service than to self-host, but how can you make those embeds responsive?

A cell phone camera mounted in a tripod

Avoid Self-hosting Your Videos

Self-hosting videos is usually a bad idea. A single video can quickly eat up your disk quota and bandwidth, especially if it gets a lot of views. At some point, your server will start to struggle and visitors won't be able to watch your videos. They'll probably just leave at that point.

Then there's the issue of formats. The HTML5 specification gave us the <video> element, but it didn't tell browsers which formats they must support. That means you have to convert and upload three different formats for each video if you want to support all major browsers — typically MP4, OGV, and WEBM.

Like I said, self-hosting videos is hard to get right. Instead, you should use a specialized service such as YouTube or Vimeo.


Styling Video Embeds

Embedded videos usually come in the form of an <iframe>, which makes them tricky to style. For example, you can give an <iframe> a 100% width but it's height won't be proportional, making it awkward on certain devices. If you want to embed videos responsively, you have to get a little creative with your stylesheet.

First off, you need to wrap the <iframe> in a container. If you're using Surreal CMS, this will happen automatically when you embed a video. Here's an example of the markup you'll get when you embed a YouTube video.

<div class="cms-embed">
  <iframe
    width="459"
    height="344"
    src="https://www.youtube.com/embed/ff8eHolqQbI?feature=oembed"
    frameborder="0"
    allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
    allowfullscreen
  >
  </iframe>
</div>

The <iframe> comes from YouTube and the <div class="cms-embed"> wrapper is added by Surreal CMS. You can ignore the width and height attributes — your stylesheet will override them.

Now let's make it responsive!

/* The embed container */
.cms-embed {
  position: relative;
  max-width: 100%;
  height: 0;
  overflow: hidden;
  padding-bottom: 56.25%; /* 16:9, calculated as 9÷16 */
}

/* The embedded iframe */
.cms-embed iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

The magic here is in the padding-bottom property, which sets the aspect ratio. You can adjust it to your liking, but 16:9 is standard for most videos. The <iframe> styles are pretty straightforward. It just stretches to fill up its container.

Clever, eh? Alas, I can't take credit for this technique. It's all over the Internet, but its first appearance was probably in Creating Intrinsic Ratios for Video on A List Apart.

That's all you have to do to make embedded videos fluid and responsive!