Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

html - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...