Glen Pierce
Glen Pierce

Reputation: 4801

How to make responsive iframe when there are multiple iframes

This works great, until I have 2 or more iframes in the same container, then they just overlap each other because they both have the same absolute position.

How do I allow for an arbitrary number of iframes inside of a container built to house iframes and maintain their aspect ratios?


From: https://www.h3xed.com/web-development/how-to-make-a-responsive-100-width-youtube-iframe-embed

The key to creating a responsive YouTube embed is with padding and a container element, which allows you to give it a fixed aspect ratio. You can also use this technique with most other iframe-based embeds, such as slideshows.

Here is what a typical YouTube embed code looks like, with fixed width and height:

<iframe width="560" height="315" src="//www.youtube.com/embed/yCOY82UdFrw" 
frameborder="0" allowfullscreen></iframe>

It would be nice if we could just give it a 100% width, but it won't work as the height remains fixed. What you need to do is wrap it in a container like so (note the class names and removal of the width and height):

<div class="container">
<iframe src="//www.youtube.com/embed/yCOY82UdFrw" 
frameborder="0" allowfullscreen class="video"></iframe>
</div>

And use the following CSS:

.container {
    position: relative;
    width: 100%;
    height: 0;
    padding-bottom: 56.25%;
}
.video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

Upvotes: 0

Views: 2980

Answers (1)

Miro
Miro

Reputation: 8650

Don't put 2 videos in the same container. Put 2 containers and wrap them in a single wrapper. Then change the width and bottom-padding to whatever you want.

.container {
    position: relative;
    width: 50%;
    height: 0;
    padding-bottom: 28.13%;
    display:inline-block;
    margin:0;
}
.video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
<div class="wrapper">
  <div class="container">
    <iframe src="//www.youtube.com/embed/3Sdes6QuPro" frameborder="0" class="video"></iframe>
  </div><div class="container">
    <iframe src="//www.youtube.com/embed/yCOY82UdFrw" frameborder="0" class="video"></iframe>
  </div>
</div>

Upvotes: 1

Related Questions