DEV Community

Pedro Pimenta
Pedro Pimenta

Posted on

Responsive iframe without a parent container

If you've built a website you have had the problem: make an iframe responsive. Maybe it was a YouTube video, maybe it was a Google Maps embed. Whatever it was, you probably did it the most popular way: wrap the iframe in a div and use padding to maintain the aspect ratio. Like this:

.videoWrapper {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 */
  height: 0;
}
.videoWrapper iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

What if you can't add the wrapper div?

I was building the v2 of a blog with 150+ articles in 3 languages and v1 was not responsive. I had to build the front end with this in mind, trying to avoid having to edit the content everywhere possible. As expected, YouTube embeds weren't wrapped in any div and changing them all would be a pain in the ass difficult. This was my solution:

iframe {
  max-width: calc(100vw - (var(--margin) * 2));
  max-height: calc((100vw - (var(--margin) * 2)) / 1.7778); /* 16:9 */
}

Of course, you do need to know how your container behaves and any margins you have. In this case I'm taking into account horizontal margins with var(--margin).

Here's a CodePen with a live example:

What do you think? What are the drawbacks? Do you see any potential problem with this solution?

Top comments (1)

Collapse
 
fentablar profile image
David Jordan

I like this solution, thank you for sharing it! One question -- where you're dividing by 1.7778 would it not be more accurate to multiply by 0.5625 instead? That way you're not sizing based on an irrational number.