Sometimes you want to scale an iframe window like an image, but the iframe doesn’t behave that way. A good example is when you embed a youtube video in your site.
A threw together a little demo on codepen showing how to accomplish this with only CSS.
If you are building a responsive site like a news site, or blog. You will probably include some video content, and when you do you will want to have the video scale properly with the container of the site.
Breaking it down
<iframe width="560" height="315" src="https://www.youtube.com/embed/wCc2v7izk8w?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
First thing you’ll have is a video, let’s say from youtube. By itself, the video will not scale. The actual video inside the <iframe>
is scaling to fit the iframe as best it can. But the iframe doesn’t have the knowledge of the size of the video inside it. That’s why you typically set the width and height on the iframe.
<div class="scale-video">
<iframe width="560" height="315" src="https://www.youtube.com/embed/wCc2v7izk8w?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>
Wrap the video in a <div>
. We’re gonna be using this as the scaling container. The key is to add a padding-top: n%
with a width: 100%;
to the container. This makes the container scale when the parent container is scaled. For a 16:9 video size, you would calculate (9 / 16 * 100) = 56.25
.scale-video {
width: 100%;
padding-top: 56.25%;
position: relative;
}
Then all you need to do is absolutely position the iframe and have it scale to fill the parent container.
.scale-video iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}