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

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/JBhp2/


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>

Quite easy with some javascript.

jQuery(function() {
    function setAspectRatio() {
      jQuery('iframe').each(function() {
        jQuery(this).css('height', jQuery(this).width() * 9/16);
      });
    }

    setAspectRatio();   
    jQuery(window).resize(setAspectRatio);
});

Tags:

Html

Css

Youtube