Responsive YouTube Video Embeds
By Flavio Copes
Learn how to make a YouTube video embed responsive by wrapping the iframe in a container div and using a CSS padding trick based on the 16:9 aspect ratio.
To make a YouTube embed responsive, wrap the iframe in a container div and use a CSS padding trick to preserve the video’s aspect ratio. The video then scales with the page, on any screen size.
The problem with embedding YouTube videos is that they are an iframe, and iframes need to be given an exact height and width, otherwise they will look funky.
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. And we need to keep the proportions, based on the video aspect ratio.
The markup
First wrap the iframe into a container div:
<div class="video-container">
<iframe src="https://www.youtube.com/embed/...." frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
You can drop the width and height attributes from the embed code. The CSS takes over from here.
The CSS
Then add this CSS to your site:
.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%;
}
Why does this work?
The trick relies on one CSS rule that surprises people: percentage values for padding-top are calculated from the element’s width, not its height.
So the ::after pseudo-element pushes the container’s height to 56.25% of its width. When the page shrinks, the width shrinks, and the height follows in perfect proportion.
The iframe is then absolutely positioned to fill the container, whatever size it happens to be.
See that magic number, 56.25%? That’s needed as a padding when the aspect ratio of a video is 16:9. (9 is 56.25% of 16).
If your video is 4:3 for example, set it to 75%.
You can calculate this percentage for any ratio with the aspect ratio calculator.
A common mistake
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.
Related posts about css: