Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaling iframes for responsive design CSS-only

A lot of sites have embedded Youtube videos. Youtube works on phones now. If responsive design is going to be a thing, why shouldn't it be a thing for iframes that contain Youtube videos?

After searching for days (on and off) I couldn't find a clear, simple solution to the problem (I'm new to HTML/CSS). It's easy to scale iframe width, but to keep height relative I found chunks of javascript, jQuery, and php, all pretty esoteric to a beginner at web design. I wanted a simple method of scaling an iframe's height to always keep a certain aspect ratio, no matter how the width changes.

To keep this from being an unanswered question, the method's below. Here are the initial settings for your iframe:

<iframe src="//www.youtube.com/embed/example_url" frameborder="0" allowfullscreen="allowfullscreen"></iframe>

That's it.

I was wondering if anyone had any other solutions as well.

like image 515
user1576628 Avatar asked Jan 10 '14 21:01

user1576628


People also ask

How do you preserve aspect ratio for an embedded iframe in a responsive website?

In the HTML, put the player <iframe> in a <div> container. In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.

Are iFrames responsive?

Unlike images and the native HTML5 video element, iframes do not scale responsively by default.


1 Answers

The solution was nested divs. A little hackey, I know, but it's a really easy solution to a problem that had too many solutions. Youtube videos keep an aspect ratio of 16:9 in this example. Your HTML should look like this:

<div id="outer">
    <div id="inner">
        <iframe src="//www.youtube.com/embed/example_url" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
    </div>
</div>

And your stylesheet:

#outer{
max-width: 640px;
max-height: 360px;
width: 100%;
height: 100%;
}

#inner{
    height: 0px;
    padding-bottom: 56.25%;
}

#inner iframe{
    width: 100%;
    height: 100%;
}

The outer div sets the maximum height and width and allows itself to scale, while the inner div uses the padding attribute to match its height to the width of the containing div (I'm pretty sure). The value should be set at (height*100/width)%, the ratio of the height to the width. The iframe then stretches to fill the whole containing div. Whitespace fills on web, so you should be just fine putting text underneath.

I can't remember exactly where I found it. It was done with images somewhere else on Stack Overflow, but I think it's relevant to have it set up to work for iframes since embedded Youtube videos are so common.

Here's a JSfiddle with the working thing.

like image 139
user1576628 Avatar answered Sep 21 '22 18:09

user1576628