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
356 views
in Technique[技术] by (71.8m points)

html - How can I make the YouTube player scale to the width of the page but also keep the aspect ratio?

I have a YouTube video I want to put on my web page.

I want to scale the video to fit to a percent of the users browser but also to keep the aspect ratio.

I have tried this:

<iframe width="87%" height="315" src="http://www.youtube-nocookie.com/embed/dU6OLsnmz7o" frameborder="0" allowfullscreen></iframe>

But that does only make the player wider, not higher.

Does I have to resort to JavaScript (or non-standard CSS)?

question from:https://stackoverflow.com/questions/7737557/how-can-i-make-the-youtube-player-scale-to-the-width-of-the-page-but-also-keep-t

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

1 Reply

0 votes
by (71.8m points)

I hit a similar issue with my site when developing some responsive CSS. I wanted any embedded Youtube objects to resize, with aspect, when switching from the desktop CSS to something smaller (I use media queries to re-render content for mobile devices).

The solution I settled on was CSS and mark-up based. Basically, I have three video classes in my CSS thus:

.video640 {width: 640px; height: 385px}
.video560 {width: 560px; height: 340px}
.video480 {width: 480px; height: 385px}

…?and I assign one of these to the Youtube content I include, depending on its original size (you may need more classes, I just picked the most common sizes).

In the media query CSS for smaller devices, these same classes are simply re-stated like so:

.video640 {width: 230px; height: 197px}
.video560 {width: 230px; height: 170px}
.video480 {width: 240px; height: 193px}

I appreciate this requires some mark-up "up-front" when including videos in your HTML (i.e. adding a class), but if you don't want to go down the Javascript route, this works pretty well -- you could re-state your video classes for as many different sizes as you require. Here's how the Youtube mark-up looks:

<object class="video640" type="application/x-shockwave-flash" value="YOUTUBE URL">
  <param name="movie" value="YOUTUBE URL"></param>
</object>

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

...