Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed YouTube iframe video 100% full width

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.

like image 499
Anthony Kung Avatar asked Feb 11 '20 08:02

Anthony Kung


People also ask

How can I get 100 iframe width?

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.


1 Answers

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%;
}
like image 98
Vizune Avatar answered Oct 25 '22 10:10

Vizune