Scaling iframes for responsive design CSS-only

2019-01-24 12:26发布

问题:

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.

回答1:

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.