Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

youtube

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)?

like image 397
Frank Avatar asked Oct 12 '11 08:10

Frank


People also ask

How do you embed full width on Youtube?

You will need to wrap the responsive youtube embed code with a div and specify a 50% to 60% padding bottom. Then specify the child elements (iframe, object embed) 100% width, 100% height, with absolute position. This will force the embed elements to expand fullwidth automatically.


2 Answers

What i believe to be the best CSS solution.

.auto-resizable-iframe {   max-width: 420px;   margin: 0px auto; }  .auto-resizable-iframe > div {   position: relative;   padding-bottom: 75%;   height: 0px; }  .auto-resizable-iframe iframe {   position: absolute;   top: 0px;   left: 0px;   width: 100%;   height: 100%; } 
<div class="auto-resizable-iframe">   <div>     <iframe frameborder="0" allowfullscreen="" src="http://www.youtube.com/embed/_OBlgSz8sSM"></iframe>   </div> </div> 

Demo http://jsfiddle.net/46vp592y/

like image 130
Darwin Avatar answered Sep 28 '22 00:09

Darwin


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> 
like image 26
Ben Avatar answered Sep 28 '22 02:09

Ben