Responsive Iframes — The Right Way (CSS Only)!

128 Comments

Join the Conversation

Responsive iframes are a cinch! Jump start using the responsive iframe CSS (using intrinsic ratios) shown below to make your iframe responsive. You’ll never ask ‘how to make iframe responsive’ again!

View Demo View Code

.iframe-container {
  overflow: hidden;
  padding-top: 56.25%;
  position: relative;
}

.iframe-container iframe {
   border: 0;
   height: 100%;
   left: 0;
   position: absolute;
   top: 0;
   width: 100%;
}

The responsive iframe CSS above demonstrates how to transform a normally fluid iframe into a responsive iframe. Just be sure to update the padding-top property to reflect the aspect ratio to make iframe responsive.

How to make iframe responsive… easy!

Trying and failing to make and iframe responsive is like a wright of passage in the web development world. The problem is iframes set to 100% become fluid, not responsive making the height a fixed size. Load up on your headache meds, because trying to overcoming this without knowing this technique will cause ‘How to make iframe responsive’ is a common question with a simple CSS-only solution, the intrinsic ratio technique.

JavaScript is NOT a solution.

I cringe every-time I see someone using JavaScript to make an iframe responsive. Even if they’re “light-weight”, their not needed. Worse, often they have their own issues with cross-browser compatibility. There’s a much simpler, easier to implement and cross-browser compliant solution to make iframes responsive called the intrinsic ratio technique. Let’s dig deeper into the responsive iframe CSS to see how it works.

Intrinsic ratios for responsive iframes.

You’ve spent countless hours designing and building the perfect responsive site. One problem — iframes. Proportionally resizing (aka. responsive iframes) these pesky little windows to another world can be frustrating. It’s easy enough to make an iframe’s width span 100% of its container. Rather, making the height resize accordingly can be tricky.

So how do you keep from blowing your top trying to make an iframe responsive?

In Resize Videos Proportionally, we learned how to use the intrinsic ratio technique to make your embedded videos responsive. We’ll use that same method and apply it to make any iframe, YouTube & Vimeo video or Google Map responsive. Only dependency is you know the aspect ratio (width x height) of the iframe.

When embedding iframes for content such as videos, most services like YouTube and Vimeo will provide you a snippet of code like the one below:

<iframe width="560" height="315" src="//www.youtube.com/embed/KMYrIi_Mt8A" allowfullscreen></iframe>

Notice I removed the frameborder attribute. If you’re using HTML5, that attribute is no longer supported.

Responsive iframe CSS

First of all, remove the width and height attributes. Keeping those attributes forces the content to stay at that size regardless of the screen size. This causes problems in responsive layouts when the screen size is smaller than the width of the iframe. Though we could use CSS to force the size, why have them if their not being used — less code is beautiful code.

<iframe src="//www.youtube.com/embed/KMYrIi_Mt8A" allowfullscreen></iframe>

Next, let’s add a container with a class around the iframe:

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

Now, we add a little touch of CSS magic to make the iframe responsive. Same way we did in the “Resize Videos Proportionally with Intrinsic Ratios“.

.iframe-container {
  overflow: hidden;
  padding-top: 56.25%;
  position: relative;
}

.iframe-container iframe {
   border: 0;
   height: 100%;
   left: 0;
   position: absolute;
   top: 0;
   width: 100%;
}

/* 4x3 Aspect Ratio */
.iframe-container-4x3 {
  padding-top: 75%;
}

IMPORTANT: Don’t forget to apply a aspect ratio class to your iframe. If you don’t, it could cause the iframe to disappear.

That it! Simple, huh? Your iframe should now proportionally resize based on the browser size. Here’s a breakdown of how it works:

Breaking It Down

  • It’s key to specify the container’s position to be relative. This allows us to absolutely position the iframe within it, which is needed to make it responsive.
  • The padding-top value is calculated based on the aspect ratio of your content. Instead of adding it to the intrinsic-container class, we added separate classes that can be appended to that element depending on the type of content you’re embedding. I prefer doing this so I’m not duplicating the container code for different aspect ratios. To find the aspect ratio of a container, use this formula: height ÷ width = aspect ratio
  • height is set to 0 because padding-bottom gives the iframe it’s height.
  • Using overflow: hidden is important because it ensures if any content does protrude outside of the container, it will be hidden and avoid screwing up the sites layout.
  • Like with most absolute positioned elements, we need to set the top and left properties so the iframe get’s put in the right place.
  • Finally, width and height are set to 100% so the iframe takes up 100% of the containers space.

Using SASS?

If you’re using SASS, use this function to find the ratio or padding-bottom of the parent container:

/**
 * Ratios
 * Returns the ratio for specified dimensions.
 */
@function ratio($width, $height) {
  return percentage( $height / $width);
}

Taking that one step further, you can create a mixin to generate ratio classes:

@mixin generateRatios($width, $height, $prefix: "ratio-") {
  $class-name: $prefix + $width + "x" + $height;

  .#{$class-name} {
    padding-bottom: ratio($width, $height);
  }
  // Output example: .ratio-16x9 {}
}

@include generateRatios(16,9); // 16x9
@include generateRatios(4,3);  // 4x3

We can use this same technique to make other types of embedded content responsive like Google Maps & Calendars. Basically, anything that uses a iframe using only CSS! If you don’t have access to edit the site stylesheets directly, here’s a nifty tool that will generate responsive embed codes for you.

Using a CSS Framework?

A lot of projects now will use some kind of CSS framework like Bootstrap, Foundation or Materialize to help with keep styling uniform throughout the project. Some frameworks already have classes that will do exactly the same as what’s above. Check out some of the examples below.

Responsive iframes in Bootstrap

Bootstrap 3.2+, use the predefined class .embed-responsive and an aspect ratio class modifier like .embed-responsive-16by9 (more listed below). This aspect ratio modifier will add the padding-top with different percentages depending on the given modifier class, then give your iframe the .embed-responsive-item class.

<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/K1K8s-tQGqY" allowfullscreen></iframe>
</div>

Other responsive iframe ratios in Bootstrap:

  • .embed-responsive-21by9
  • .embed-responsive-16by9
  • .embed-responsive-4by3
  • .embed-responsive-1by1

You can of course create your own modifier class:

.embed-responsive-10by3 {
   padding-top: 30%;
}

Responsive iframes in Materialize

If you are using Materialize CSS, then you don’t need your own classes either. Just add the .video-container class to your wrapper:

<div class="video-container">
  <iframe src="https://www.youtube.com/embed/K1K8s-tQGqY" frameborder="0" allowfullscreen></iframe>
</div>

Responsive iframes in Foundation

<div class="responsive-embed">
  <iframe src="https://www.youtube.com/embed/K1K8s-tQGqY" frameborder="0" allowfullscreen></iframe>
</div>

Aspect ratio modifier classes are set in your $responsive-embed-ratios map in your Foundation settings file:

$responsive-embed-ratios: (
  default: 16 by 9,
  vertical: 9 by 16,
  panorama: 256 by 81,
  square: 1 by 1,
);

Responsive iframes Using JS

What if you don’t know the aspect ratio? Let’s say you have content authors creating interactives with each having different dimensions. Without knowing the aspect ratio of the iframe, it’s not easy to implement the intrinsic ratio technique.

You can overcome this problem by using JS:

// Find all iframes
var $iframes = $( "iframe" );

// Find &amp;amp;#x26; save the aspect ratio for all iframes
$iframes.each(function () {
  $( this ).data( "ratio", this.height / this.width )
    // Remove the hardcoded width &amp;amp;#x26; height attributes
    .removeAttr( "width" )
    .removeAttr( "height" );
});

// Resize the iframes when the window is resized
$( window ).resize( function () {
  $iframes.each( function() {
    // Get the parent container&amp;amp;#x27;s width
    var width = $( this ).parent().width();
    $( this ).width( width )
      .height( width * $( this ).data( "ratio" ) );
  });
// Resize to fix all iframes on page load.
}).resize();

Let’s Sum It Up!

Say Goodbye to embedded content breaking your layouts with the intrinsic ratio technique. We’ve walked through how just a little bit of code can easily make your iframes and other embedded content responsive friendly.

How do you embed third-party content on your responsive website? Do you have a nifty technique or trick to accomplish responsive embedded content? What about your workflow for embedding content like Google Maps, YouTube, etc? I’d love to hear from you. Comment below with your thoughts.


Additional Resources

Check out these other great articles about making embedded content responsive:

Comments

  1. at 12:52 am

    Hello, I found this by accident but I was wondering.
    I agree with: “remove the I-frame height and width”, sort of, I just made the width “AUTO” and it seemed to solve everything?
    Now, OK, I am not a developers you know what, so why is this not an option?
    Cheers

  2. at 7:45 pm

    Great for media that requires an aspect ratio. But, how can we adapt this to static content such as forms and pages?

  3. Lloyd
    at 1:12 am

    Ben.… YOU ARE BRILLANT!
    Followed your plain-jane simple instructions, and SOLVED in under 2 minutes.
    I am no longer a victim to the mighty IFRAME!!! 😛
    Thank you!!!

  4. Tony
    at 5:25 am

    What about if the iframe contains dynamic content that changes height when a button is clicked inside the frame? It seems like ever site on the subject just recycles the same code. It all only works for content with fixed a fix height/width.

  5. Eric Faucett
    at 5:45 pm

    Thank you for this awesome article! I was super frustrated because I had a Facebook Embedded video that WOULD NOT load responsive on mobile!

    This is extremely valuable, worked like a CYNCH and I’m grateful!! Super easy to implement and expert advice ALL AROUND!!!

  6. at 7:15 am

    What if I want a bit more space around the iframe (left and right sides) – if I change the height and width to 90% will that break anything else. Also, once I do that, is there a way to then center the iframe on the page (left to right)? Thanks!

    • at 7:17 am

      You can set the width to whatever you’d like, just update the padding-top to keep your aspect ratio. For centering, you can use margin.

      .iframe {
        margin: 0 auto;
      }
  7. at 1:46 pm

    Hello

    When i use your code to make a youtube video responsive within its iframe it makes it take up the whole screen due to the 100% height and width values. When i shrink the values it’s still pinned to the top left of the page. I have the container for the iframe within a div grid for the page layout.

    Is there any tips or tricks to get this to work within a div grid?

    Thanks for your website – its a great resource!

    Best
    Josh

    • at 8:17 pm

      Sounds like you’re missing something. Double check your code and make sure the container you have around your iframe has it’s position set to relative.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

All comments are held for moderation. I'll publish all comments that are on topic and not rude. You'll even get little stars if you do an extra good job.

You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.

Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.

%d bloggers like this: