Make your embedded videos responsive with CSS
When you insert an embedded video from Youtube, Vimeo, Dailymotion or any other video site, you’re asked to paste an HTML snippet into your website (usually an ìframe
or a div
wrapper) but the problem is, usually its width is fixed.
With the importance of responsive web design, we need to make these video embeds responsive, meaning its width automatically changes and adapts to its parent container’s width.
It’s no discussion that a pure CSS solution that works across all browsers (old and modern) is going to win over any other method.
This is what an article from CSSTricks (in 2009) proposes for iframe
, embed
and object
tags:
.videoWrapper {
position: relative;
padding-bottom: 56.25%; /* 16:9 */
padding-top: 25px;
height: 0;
}
.videoWrapper iframe,
.videoWrapper embed,
.videoWrapper object {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
This way you will force these tags to take all the size of the wrapping div
(hence the 100%
size values).
Now, to make use of this class all you need to do is insert an embedded video code inside a div with the class of videoWrapper
.
<div class="videoWrapper">
<iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ?si=3Wk6DwA4qCjDQRU2" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div>
If you are a Tailwind user, you can achieve the same with these classes:
<div class="relative pb-[56.25%]">
<iframe class="absolute inset-0 w-full h-full" width="560" height="315" ...></iframe>
</div>
Here’s how it looks like live and in colour:
(yes, I know, very mature…)