Responsive YouTube Video Embeds

By

Make a YouTube embed responsive with CSS aspect-ratio (16:9), and keep the older padding-top hack only as a fallback for very old browsers.

~~~

To make a YouTube embed responsive, wrap the iframe in a container and set aspect-ratio: 16 / 9. The video scales with the page and keeps its proportions. No fixed pixel height needed.

The problem with embedding YouTube videos is that they are an iframe, and iframes need a size. The embed code YouTube gives you has fixed pixel dimensions, something like width="560" height="315". That looks fine on a desktop. On a phone, the video overflows the screen or leaves a big gap.

The modern way: aspect-ratio

First wrap the iframe in a container:

<div class="video-container">
  <iframe
    src="https://www.youtube.com/embed/...."
    title="YouTube video"
    allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
    allowfullscreen
  ></iframe>
</div>

Drop the width and height attributes from the embed code. Also drop the old frameborder="0" attribute. CSS handles the border.

Then add this CSS:

.video-container {
  width: 100%;
  aspect-ratio: 16 / 9;
}

.video-container iframe {
  display: block;
  width: 100%;
  height: 100%;
  border: 0;
}

Every modern browser has supported aspect-ratio since 2021. The browser keeps the box at 16:9 as the width changes. For a 4:3 video, use aspect-ratio: 4 / 3 instead.

The display: block matters. Without it the iframe sits on a text line, and the container grows a few pixels taller than 16:9 to make room for the line.

I wrote a deeper guide on the CSS aspect-ratio property if you want the math and layout details. You can also play with ratios in the aspect ratio calculator.

The older padding-top hack

Before aspect-ratio shipped everywhere, people used a padding trick. Percentage padding-top is calculated from the element’s width, so 56.25% recreates 16:9 (9 is 56.25% of 16). For 4:3, use 75%.

You only need this if you still support browsers without aspect-ratio. For new pages, prefer the first approach.

.video-container {
  overflow: hidden;
  position: relative;
  width: 100%;
}

.video-container::after {
  padding-top: 56.25%;
  display: block;
  content: '';
}

.video-container iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 0;
}

Be careful with position: relative on the container. If you forget it, the iframe’s position: absolute positions it against the nearest positioned ancestor, or the page itself. The video ends up stretched over some other part of the layout.

If your embed looks fine in width but sits in the wrong place, that’s almost always the missing position: relative.

Tagged: CSS · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about css: