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%;
}
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>
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%;
}
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>
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 */
}