How to Make YouTube Video Embeds Responsive With CSS

Learn how to embed YouTube videos on your website and make it fully responsive from mobile to desktop devices, with CSS.

If you copy the embed video code from YouTube and in you get an <iframe> wrapper that looks similar to this:

<iframe
  width="560"
  height="315"
  src="https://www.youtube.com/embed/uga8GWzdv3c"
  frameborder="0"
  allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
  allowfullscreen
></iframe>

Unfortunately, iframes require a fixed height and width to display with a correct aspect ratio in the browser. This makes iframes incompatible with responsive design out of the box.

Fortunately, you can make your video embeds by wrapping your iframe in a parent container:

<div class="youtube-video-container">
  <iframe
    width="560"
    height="315"
    src="https://www.youtube.com/embed/uga8GWzdv3c"
    frameborder="0"
    allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
    allowfullscreen
  ></iframe>
</div>

And then style your video container with CSS:

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

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

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

Calculating aspect ratios

Are you wondering what the 56.25% padding-top is about? It’s based on the aspect ratio of YouTube videos, which is 16/9.

To get the exact padding value to make your video container responsive, you just need to find out how many % the height value is of the width value:

9/16 * 100 = 56.25%

9 is 56.25% of 16.

If your embedded video’s aspect ratio is 4:3, you would calculate the video container’s top padding like this:

3/4 * 100 = 75%

And so on.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on