DEV Community 👩‍💻👨‍💻

Cover image for Embed responsive YouTube videos in 2021
Maxime
Maxime

Posted on

Embed responsive YouTube videos in 2021

If you just want the code, scroll down.

The history

For a long time, web developers have had to rely on obscure CSS tricks to embed responsive YouTube videos on their website.

If you've ever had to do this yourself, you probably relied on a trick similar to this:

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

.video-container iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
Enter fullscreen mode Exit fullscreen mode

Combined with markup like this:

<div class="video-container">
  <iframe
    src="https://www.youtube.com/embed/msizPweg3kE"
    frameborder="0"
    allow="accelerometer; autoplay; encrypted-media; gyroscope;"
    allowfullscreen></iframe>
</div>
Enter fullscreen mode Exit fullscreen mode

What's the 56.25% number? It represents of the aspect ratio of the video, which is usually 16/9 on YouTube (9 is 56.25% of 16.)

Using the aspect-ratio property

Create a class and use the aspect-ratio property to automatically set the width and height of your video based on its container:

.video {
  aspect-ratio: 16 / 9;
  width: 100%;
}
Enter fullscreen mode Exit fullscreen mode

In your HTML, apply the class you created (.video, in my case) to your iframe:

<iframe
  class="video"
  src="https://www.youtube.com/embed/msizPweg3kE"
  frameborder="0"
  allow="accelerometer; autoplay; encrypted-media; gyroscope;"
  allowfullscreen></iframe>
Enter fullscreen mode Exit fullscreen mode

And that's it! No need for fancy tricks anymore.

Browser support

This feature is safe to use in all modern browsers, as you can see on caniuse.com. If you need to support older browsers, I recommend using the supports media query to make your UI consistent:

@supports not (aspect-ratio: 1) {
  /* ... implement your fallback here */
}
Enter fullscreen mode Exit fullscreen mode

Header image by Christian Wiediger on Unsplash

Top comments (5)

Collapse
 
scheiber profile image
Jonathan Scheiber

Thanks for this. Works great.

Collapse
 
berkcan profile image
BeRk CaN

Thank you os much you saved me

Collapse
 
aborruso profile image
Andrea Borruso

Thank you very much

Collapse
 
shevitza profile image
Evgenia Hristova

Thank you, very helpfull and clear!

Collapse
 
siddacool profile image
Siddhesh Mangela

Thanks a lot

Become a Moderator Do you want us to help make DEV a better place?

Fill out this survey and help us by becoming a tag moderator here at DEV.