With The Youtube Embedded Iframe

We can see there are a few attributes as follows: width, height, src and more. Now the biggest issue with two of the attributes is the width and height that are causing all the issues. It would be extremely nice to just be able to remove these two attributes but we don’t need to. By utilizing CSS we can change the width and height dynamically when viewing the iframe from different screen sizes.

<iframe width="560" height="315" src="https://www.youtube.com/embed/BEiiZZPXi1I" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen=""></iframe>

Contain The Iframe

Now let’s contain the iframe with a div with a class of .video-container as shown below.

<div class="video-container">
<iframe width="560" height="315" src="https://www.youtube.com/embed/BEiiZZPXi1I" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen=""></iframe>
</div>

Add The CSS Magic!

Now making the container wrapper responsive with the .video-container class. Now let’s review what the wrapper is doing.

  • position: relative All child elements will position themselves in relation to this container.
  • padding-bottom: 56.25% Calculated out of the aspect ratio of the video, 16:9 will be 56.25% 4:3 will be 75%
  • padding-top: 35px This is specific to YouTube embedded videos
  • height: 0 Padding-bottom set at 56.25% will give the height that is needed for the video to show up responsive.
  • overflow: hidden Ensures that any unwanted content outside of the video will not be shown.

Next is to style the iframe itself with the second part of the CSS shown below.

  • position: absolute Will position itself inside the parent element with a perfect fit.
  • top: 0 We want to make sure the element sits right at the top of the parent element.
  • left: 0 Also making sure the element sits on the left side of the parent element nicely.
  • width: 100% Now by declaring 100% width will expand the iframe to fit based on the parent elements full width.
  • height: 100% Now by declaring 100% height will expand the iframe to fit based on the parent elements full height.
.video-container {
    position: relative;
    padding-bottom: 56.25%;
    padding-top: 35px;
    height: 0;
    overflow: hidden;
}

.video-container iframe {
    position: absolute;
    top:0;
    left: 0;
    width: 100%;
    height: 100%;
}
Categories: Blog

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *