Handling media is quite often one of the most challenging parts of responsive web design. Images tend to be pretty simple to manage with a little CSS, but iframes are a lot trickier to work with. Sure, you can set a max-width of 100%, but it’s not going to keep the same aspect ratio as it resizes like images do. Thankfully, we can work a little mathematical magic with jQuery. Here’s a snippet that I’m using on a current project that embeds a lot of videos with iframes:

First, we cache all of our iframes into a variable, then we write a function to do the actual work. In the function, we set variables for the item, the item’s width and height, the width of the items direct container, the aspect ratio of the item, and finally we use the ratio to set a new height. Then we simply apply the new width and height to the item.

After the function is created, we create another function that applies the first one to our cache of iframes. Finally, we fire the second function on load and on window resize. Boom! Responsive iframes.

7 thoughts on "Responsive Iframes"

  1. Alex says:

    Thank you. Great example of what jQuery/JavaScript can do.

  2. Can you give me a working example of this? I’m having a hard time getting it to work on the site I’m doing. Thanks!

    1. thdadmin says:

      Here’s a codepen that shows it working http://codepen.io/tammyhart/pen/zHysv

      1. Thanks! Yours works a lot better than what I ended up doing.

        Interesting video choices. Made my morning. You have a beautiful site, too. 🙂
        BTW, you left out the “http:” in the video URLs.

        Carl

  3. iModDesign says:

    Thank you this useful for me.

  4. Kyle Shevlin says:

    Thank you Tammy. Great solution for one of my websites. I wanted to create a landing page for my Bandcamp albums (which are iframes) on it, and this does the trick. Will be using this a lot in the future.

    1. thdadmin says:

      so glad I could help! 🙂

Leave a Reply

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