Just thought someone will be interested in knowing how to embed a YouTube iframe or any 16:9 video (e.g. Twitch live widget, Vimeo etc.)
YouTube usually gives you a fixed size video width="560"
height="315"
. But usually, people want to embed it as full width so that it looks good and also responsive.
But setting it to 100vw will just mess up the site as it goes out of the container and also the height cannot be determined.
So the iframe has to be 100% width according to its container, which can be done by simply adding width="100%"
. But the height is still messed up, setting it to 100% will not work.
And it has to work when viewer changes their screen size, either moving the phone from vertical to horizontal or maximizing windows.
To get the iframe to properly use 100% the parent needs to be 100%. In newer doctypes the html and body tag are not automatically 100%. When I added height:100% for html and body then it worked flawlessly.
I know this question is tagged with JavaScript but the solution is a lot more simpler with CSS. All you need to do is wrap the video embed inside a div and apply CSS.
<div class="videoWrapper">
<!-- Video embed goes here -->
</div>
.videoWrapper {
position: relative;
padding-bottom: 56.25%; /* 16:9 */
height: 0;
overflow: hidden;
}
.videoWrapper iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With