How to embed YouTube iframe video 100% full width

13,106

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%;
}
Share:
13,106
Anthony Kung
Author by

Anthony Kung

Hi, I'm an Electrical &amp; Computer Engineering student at Oregon State University also minoring in computer science.

Updated on June 06, 2022

Comments

  • Anthony Kung
    Anthony Kung almost 2 years

    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.

  • Admin
    Admin almost 3 years
    What did I do wrong, I couldn't get it to work? jsfiddle.net/xa1jtyr5
  • DragonLord
    DragonLord over 2 years
    If you try to enlarge or move the video so it covers some of its containers, if any of the parent containers quietly have overflow: hidden or overflow: auto set, the video will get clipped. Even if you give it high z-index. A solution is to track down the offending container, using a website Developer-tool code inspector, and then override it locally to overflow: visible. Alternatively, you should be able to use the transform trick to start a new z stack on the video div, and break out of the parent container's confinement.