How to make Iframe and other embedded content behave responsively?

It’s easy to make an iframe’s width dimension to 100% of its container, but sizing it’s height is tricky — especially if the content of the iframe changes height depending on page width within the iframe.


<div class="responsive-container responsive-container-16x9">
  <iframe src="//www.youtube.com/embed/KMYrIi_Mt8A" allowfullscreen></iframe>
</div>

To achieve responsive iframe we can use following CSS codes.

The key idea is to specify the parent container’s position to be relative. This allows to absolutely position the iframe within it, which is needed to make it responsive.


responsive-container {
  position: relative;
  height: 0;
  overflow: hidden;
}
/* 16x9 Aspect Ratio */
.responsive-container-16x9 {
  padding-bottom: 56.25%;
}
/* 4x3 Aspect Ratio */
.responsive-container-4x3 {
  padding-bottom: 75%;
}
.responsive-container iframe {
  position: absolute;
  top:0;
  left: 0;
  width: 100%;
  height: 100%;
}

Iframe should now proportionally resize based on the browser size.

Other Techniques:

Use of Pym.js:

Pym.js embeds and resizes an iframe responsively (width and height) within its parent container. It also bypasses the usual cross-domain issues.

Fix using Jquery:


var $iframes = $( "iframe" );
// Find and save the aspect ratio for all iframes
$iframes.each(function () {
  $( this ).data( "ratio", this.height / this.width )
    // Remove the hardcoded width and height attributes
    .removeAttr( "width" )
    .removeAttr( "height" );
});
// Resize the iframes when the window is resized
$( window ).resize( function () {
  $iframes.each( function() {
    // Get the parent container's width
    var width = $( this ).parent().width();
    $( this ).width( width )
      .height( width * $( this ).data( "ratio" ) );
  });
// Resize to fix all iframes on page load.
}).resize();

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *