Resize Iframe To Fit Content (Same Domain Only) - CSS-Tricks

Normally you set and width and height for iframes. If the content inside is bigger, scrollbars have to suffice. The script below attempts to fix that by dynamically resizing the iframe to fit the content it loads.

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script> <script type='text/javascript'> $(function(){ var iFrames = $('iframe'); function iResize() { for (var i = 0, j = iFrames.length; i < j; i++) { iFrames[i].style.height = iFrames[i].contentWindow.document.body.offsetHeight + 'px';} } if ($.browser.safari || $.browser.opera) { iFrames.load(function(){ setTimeout(iResize, 0); }); for (var i = 0, j = iFrames.length; i < j; i++) { var iSource = iFrames[i].src; iFrames[i].src = ''; iFrames[i].src = iSource; } } else { iFrames.load(function() { this.style.height = this.contentWindow.document.body.offsetHeight + 'px'; }); } }); </script>

Will resize an iframe like this:

<iframe src="content.html" class="iframe" scrolling="no" frameborder="0"></iframe>

View Demo

Still problematic…

  1. The source of the iframe content must reside on the same domain
  2. if the content inside the iframe changes height, this won’t adapt
  3. I left Google Analytics code off the demo above, as when I added it in it seems to interfere and not resize the iframe, despite seemingly generating no errors.
Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.

Comments

  1. Callum Permalink to comment# October 16, 2009

    Excellent, this is exactly what I was looking for :)

    Loading... Reply
    • Maku Permalink to comment# January 7, 2010

      does anyone experienced bug on IE? …IE didnt resize the iframe instead it rendered a fixed height for the iframe. Any fix yet? Thanks

      Loading...
    • Leif Permalink to comment# June 5, 2013

      Just what I needed! Awesome fix man. Thanks!

      Loading...
  2. Thall Permalink to comment# May 19, 2010

    I doesnt work in IE 7 or 8. Tested in IETester

    Loading... Reply
  3. Juliano Dasilva Permalink to comment# August 31, 2010

    Hi Chris, I’m wondering if you know of any script that would adapt the height of the iframe if the content inside the iframe changed height. Thanks!

    Loading... Reply
  4. Nancy Permalink to comment# March 3, 2011

    I am real new at this. Where within the page code do I put your code?

    Loading... Reply
  5. eJames Permalink to comment# May 30, 2011

    MAN! this is what i needed, i dont know why i didnt think of it, absolute lifesaver

    -cheers

    Loading... Reply
  6. dhana Permalink to comment# June 14, 2011

    Hi,

    above code working in ie7 fine.but its not working in ie8.could u please send the code for that.

    Loading... Reply
  7. Melisande Permalink to comment# July 16, 2011

    excellent! thanks :D

    Loading... Reply
  8. skyrail Permalink to comment# July 19, 2011

    tested with success in IE9 for windows. Set doctype transitional on top of html code.

    Still need some tweaks to adjust the page width I want.

    Loading... Reply
  9. Soshian Permalink to comment# October 17, 2011

    Hello !!! Your code not work in chrome explorer ( your code = other codes ). Please send true code for me. thanks.

    Loading... Reply
  10. pain Permalink to comment# November 18, 2011

    hello everyone. same question here. where should i put script above.

    thank you

    Loading... Reply
  11. Muzza Permalink to comment# December 4, 2011

    Thanks for the script! I added styles to the iframe for IE, FF & Chrome.

    Thanks Muz

    Loading... Reply
    • Muzza Permalink to comment# December 4, 2011

      style=”height:100%;width:100%;min-height:800px;”

      Loading...
  12. George Permalink to comment# December 23, 2011

    Thanks for the script. I decided to used it for now. If it breaks for different browsers I’ll try and think or find something else. Meanwhile I also found this: http://www.iframehtml.com/iframe-scripts.html#resizeable-iframe

    Thought I’d share it here. Seems easy and quick to use, the demo page works fine but this solution didn’t agree with my code.

    Loading... Reply
  13. Stas Permalink to comment# January 27, 2012

    Do not work with IE 6:( Maybe I can set minimal height?

    Loading... Reply
  14. Jtroutman Permalink to comment# February 29, 2012

    I got around the cross domain issue (atleast for subdomains) with document.domain = “yourdomain.com”

    Loading... Reply
    • BDeMers Permalink to comment# October 22, 2013

      Pardon my ignorance here but can you please explain where you inserted the document.domain?

      Loading...
  15. me Permalink to comment# March 13, 2012

    Works like a charm. Thanks.

    Loading... Reply
  16. Rob Permalink to comment# May 1, 2012

    Does anybody know how to do this when you embed a PDF in the iframe? I’m generating the PDF dynamically with a server-side script (ASP.NET MVC). The problem I’ve found is that, when the .load function, the PDF hasn’t been rendered to the iframe yet, so the “current” height is something like 150px (default maybe).

    Any ideas?

    (Great post by the way!)

    Loading... Reply
  17. Emman Permalink to comment# July 27, 2012

    Try to add edit your code on if statement replace your code on this code, hope it works:

    if ($.browser.safari || $.browser.opera || $.browser.msie && $.browser.version==”6.0″) {

    iFrames.load(function(){ setTimeout(iResize, 0); });

    Loading... Reply
  18. tim Permalink to comment# August 13, 2012

    The height DOES adapt to changing content in the iframe, in latest IE and Firefox!

    Loading... Reply
  19. Thierry Permalink to comment# August 14, 2012

    I am from Brasil and this tuto is show, show, show. excellent! thanks :D

    Loading... Reply
  20. Peter Drinnan Permalink to comment# September 27, 2012

    I didn’t think this was possible for some reason. I’m building a site right now with various tables loading from another site (sport scores). Being able to resize the iframe like this will make it look like part of the main site. Awesome!

    Loading... Reply
  21. Xaver Permalink to comment# November 13, 2012

    This works for me even on IE and it doesn’t require jQuery

    Loading... Reply
  22. Christoph Permalink to comment# December 3, 2012

    Hey, so is there maybe an update on this article? I have tried several versions and i still get problems with Safari for example. Is there really a workaround that works on all browsers IE7+? Cheers

    Loading... Reply
  23. Shweta Permalink to comment# January 17, 2013

    Hello, thanks for useful script. It works fine for file from same domain. But I want to show Google spreadsheet in iframe. and above script does not work for me. Please can you suggest solution.

    Loading... Reply
  24. Halfist Permalink to comment# February 20, 2013

    In Firebug I see next error:

    Error: Permission denied to access property ‘document’

    this.style.height = this.contentWindow.document.body.offsetHeight + ‘px’;

    Loading... Reply
    • Anil Kachhadiya Permalink to comment# November 14, 2013

      Hi, i am trying to add iframe blog using this code.

      Just want your help, how you removed that error ?

      Please reply.

      Thanks.

      Loading...
  25. Ayyash Permalink to comment# May 23, 2013

    You can do the same by making the script run inside the iFrame body, when body loads, find the iframe in window.top and change its style height

    unfortunately I found a very nasty bug on IE9 (fixed in IE10), when I change height, it some how affects the main window, and rolls down my css media to match the rule that fits the iframe WIDTH! so if iframe width is 900px, it will render the whole page under media rule @media only screen and (max-width: 960px)

    :'( how do we prevent an iframe change in height from re-running the parent css media queries?

    Loading... Reply
    • Yvonne Permalink to comment# October 7, 2015

      Hi,

      Did you solve this problem? We’re experiencing the same.

      Loading...
  26. ArleyM Permalink to comment# June 6, 2013

    Problematic issue #2 can be addressed with a touch of JS after the function! Here’s a trick @grahamkennery showed me:

    setInterval(iResize, 1000);

    Essentially this will ask the function to double-check its work every second. This is ideal if the source of the iframe changes size!

    Loading... Reply
  27. Rico Permalink to comment# June 26, 2013

    @ArleyM

    Either I don’t know where to put the setInterval(iResize, 1000); or it just doesn’t work.

    Hope it works and I’m just plain wrong

    Thanks!

    Loading... Reply
    • Blake Permalink to comment# December 9, 2013

      Hi Rico, This is working for me….

      var iFrames = $('.myFrame'); function iResize() { for (var i = 0, j = iFrames.length; i < j; i++) { iFrames[i].style.height = iFrames[i].contentWindow.document.body.offsetHeight + 'px';} } if ($.support.safari || $.support.opera) { iFrames.load(function(){ setTimeout(iResize, 0); }); for (var i = 0, j = iFrames.length; i < j; i++) { var iSource = iFrames[i].src; iFrames[i].src = ''; iFrames[i].src = iSource; } } else { iFrames.load(function() { this.style.height = this.contentWindow.document.body.offsetHeight + 'px'; }); } setInterval(iResize, 1000);

      Also, note that recent versions of jQ need the if ($.browser.safari || $.browser.opera) { bit to be updated to if ($.support.safari || $.support.opera) {

      Hope this helps, Thanks!

      Loading...
  28. tin Permalink to comment# July 9, 2013

    Wow.. nice stuff! thanks a lot

    Loading... Reply
  29. Pranav Ballaney Permalink to comment# September 27, 2013

    But what if it’s on another domain? Like, fb comments?

    Loading... Reply
  30. mister Permalink to comment# October 30, 2013

    Help Me How to add CSS class and control elements inside of the Iframe using javaScript… Please Please Help Thanks

    Loading... Reply
  31. Clint Crocker Permalink to comment# December 20, 2013

    This worked perfect. I am impressed with it!

    Loading... Reply
  32. hddung89 Permalink to comment# February 6, 2014

    thanks you, great tips

    Loading... Reply
  33. Anbuselvan Permalink to comment# March 10, 2014

    yes, its works ,thanks but 1.i got the access denied error in script 2. my Iframe have static content its working fine. 3.if I have combox box ,based on that I can load the content.its not working.

    Loading... Reply
    • Anbuselvan Permalink to comment# March 10, 2014

      yes, its works ,thanks very much.

      while I load dynamic content ,I used //parent page function Resize() { var iFra = $(‘iframe’); for (var i = 0, j = iFra.length; i < j; i++) { iFra[i].style.height = iFra[i].contentWindow.document.body.offsetHeight + ‘px’; } }

      // Iframe page. parent.Resize();

      Loading...
  34. Lakshya Permalink to comment# March 21, 2014

    That’s cool but I need codes for that when we click a text, a page with forms etc. comes up.

    Loading... Reply
    • Anbuselvan Permalink to comment# March 24, 2014

      This is My Parent Page: I Have two Iframe with different page with dynamic Content.

      <script type='text/javascript'> $(function () { var iFrames = $('iframe'); function iResize() { for (var i = 0, j = iFrames.length; i < j; i++) { iFrames[i].style.height = iFrames[i].contentWindow.document.body.offsetHeight + 'px'; } } if ($.browser.safari || $.browser.opera) { iFrames.load(function () { setTimeout(iResize, 0); }); for (var i = 0, j = iFrames.length; i < j; i++) { var iSource = iFrames[i].src; iFrames[i].src = ''; iFrames[i].src = iSource; } } else { iFrames.load(function () { this.style.height = this.contentWindow.document.body.offsetHeight + 'px'; }); } }); function Resize() { var iFra = $('iframe'); for (var i = 0, j = iFra.length; i < j; i++) { iFra[i].style.height = iFra[i].contentWindow.document.body.offsetHeight + 'px'; } }

      Privacy Policy You may choose to give us personal information, such as your name and address or e-mail id that may be needed, for example, to correspond with you, to download our white papers or to provide you with a subscription. If you tell us that you do not want us to use this information as a basis for further contact with you, we will respect your wishes. We intend to protect the quality and integrity of your personally identifiable information.

      Cookies, and other technologies

      </div> <div style="border: 1px solid Blue;">

      **

      **

      Anbuselvan

      <div>

      **

      **

      Iframe Page:

      In this I am used Combo and GridView .Based on Combo value the gridview row has been binded. (Dynamically Loaded data from DB.)

      function loadgrid() { var applyTimeList = document.getElementById('DropDownList1'); var value = applyTimeList.options[applyTimeList.selectedIndex].value; $.ajax({ type: "POST", url: "loadadminlist.aspx/CurrentUpdate", data: '{name: "' + value + '" }', contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, failure: function (response) { alert(response.d); }, error: function (response) { alert(response.d); } }); } function OnSuccess(response) { var xmlDoc = $.parseXML(response.d); var xml = $(xmlDoc); var customers = xml.find("vpagetitle"); var row = $("[id*=GridView1] tr:last-child").clone(true); $("[id*=GridView1] tr").not($("[id*=GridView1] tr:first-child")).remove(); var $grid = $("[id*=GridView1]"); for (i = 0; i < customers.length; i++) { var cont = "<tr><td>" + customers[i].textContent + "</td></tr>"; $grid.append(cont); } parent.Resize(); } </script> <div> <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="false" onchange="javscript:loadgrid();" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList> </div> <div> <br /> </div> <div class="childdiv"> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText="No data found!"> <Columns> <asp:BoundField ItemStyle-Width="150px" DataField="vpagetitle" HeaderText="vpagetitle" /> </Columns> </asp:GridView> </div> <div> [email protected] </div> </form> Loading...
  35. Tantan Permalink to comment# August 19, 2014

    Not work for me

    Loading... Reply
  36. [email protected] Permalink to comment# October 18, 2014

    Hi. Thank you very much for this, it could be a life saver. I have a concern, and a problem to ask if you know of any fix, please. The concern is, I have 2 iFrames within one DIV, the first and topmost one if for a range of “thumbnail” images of photographs that a visitor can look and select. The selected one then loads the full size photo the iFrame below. It works wonderfully apart from the fact that the photographs are all different heights, so the default page has to all different sizes to accommodate…….. :-( Your script works wonderfully in adjusting the page to suit the size of the photograph, apart from the fact that it seems to cut off a small portion of both the Thumbnail and the main photo frame along the bottom……. Any thoughts please would be greatly appreciated. Below is the “iFrame” code with your fix put in place. Thank you very much in advance. Glen

    $(function(){ var iFrames = $('iframe'); function iResize() { for (var i = 0, j = iFrames.length; i &lt; j; i++) { iFrames[i].style.height = iFrames[i].contentWindow.document.body.offsetHeight + 'px';} } if ($.browser.safari || $.browser.opera) { iFrames.load(function(){ setTimeout(iResize, 0); }); for (var i = 0, j = iFrames.length; i &lt; j; i++) { var iSource = iFrames[i].src; iFrames[i].src = ''; iFrames[i].src = iSource; } } else { iFrames.load(function() { this.style.height = this.contentWindow.document.body.offsetHeight + 'px'; }); } }); &nbsp;</code>

    P.S. I do not know what/where “triple backticks are…….. sorry

    Loading... Reply
  37. JayJu Permalink to comment# October 24, 2014

    Is there any way to ad say 25 pixels to the offset query, I have a page that I want scrolling on when it’s resized, but when the iframe fits in the window, there seem to be 25 pixels that are still not accounted for, so it always has a scrollbar for that extra 25 pixels.

    Thanks

    Loading... Reply
  38. JayJu Permalink to comment# October 26, 2014

    is there any way to use scrollTop in this code instead of, offsetHeight? I can’t seem to get it to work, the iframe just disappears

    Loading... Reply
  39. Matt Flaherty Permalink to comment# February 20, 2015

    Hi. The .browser property has been removed from jQuery and browser sniffing is not recommended. What is the actual quirk that requires the workaround for safari and opera? If known, this can probably be feature detected. Thanks.

    Loading... Reply
  40. Testtem Permalink to comment# June 15, 2015

    Amazing. It’s posting that I’m looking for.Tks verymuch

    Loading... Reply
  41. Gino Côté Permalink to comment# August 5, 2016

    I tryed one zillions of scripts to make it work on IE and it never worked, same for this one but it work here… sometime http://fiddle.jshell.net/onigetoc/korxwt0e/

    Loading... Reply
  42. Gino Côté Permalink to comment# August 5, 2016

    And here my first attemps to create a jQuery iframe fit resizer… but as usual, it do not work on I.E. https://github.com/onigetoc/jQuery-iframe-resizer/

    Loading... Reply
  43. Varsha Permalink to comment# November 1, 2016

    Hi, I am facing a problem in the script when i am using source in the same file . for example:

    The script is not working for single word , its only working upto particular lenght .

    Please Help Thanks

    Loading... Reply
    • Varsha Permalink to comment# November 1, 2016

      Hi, I am facing a problem in the script when i am using source in the same file . http://codepen.io/varshagn/pen/NRQBbY

      The script is not working for single word , its only working upto particular lenght .

      Please Help Thanks

      Loading...
  44. Priya Permalink to comment# March 6, 2017

    Hi All,

    We have 3 frame in that if i use 1st frame the size should be 50 2nd & 3rd should be 25 like that it want auto change and if i use 2 nd frame the size automatically 50 and other 2 should be 25

    Using CSS how can i do can anyone suggest

    Loading... Reply
    • carol sunday Permalink to comment# May 7, 2017

      I’m a rank amateur, and even for me, so easy to use. Thank you!

      My iframes look perfect in all browsers except chrome.

      I couldn’t find a fix, so thought maybe just separating out chrome and giving it a set height so my iframes wouldn’t be so truncated might be at least better than nothing.

      But I can’t seem to get it to work. (iframe heights are showing up at around 150px).

      What might I be doing wrong with this?

      $(function(){ var iFrames = $('iframe'); function iResize() { for (var i = 0, j = iFrames.length; i < j; i++) { iFrames[i].style.height = iFrames[i].contentWindow.document.body.offsetHeight + 'px';} } //am using jquery 1.9.1 so switched from browser to support if ($.support.safari || $.support.opera ) { iFrames.load(function(){ setTimeout(iResize, 0); }); for (var i = 0, j = iFrames.length; i < j; i++) { var iSource = iFrames[i].src; iFrames[i].src = ''; iFrames[i].src = iSource; } } //here's the new bit: if ($.support.chrome ) { iFrames.load(function(){ this.style.height = "550px"; }); } //end new bit ... why doesn't this return a height of 550 px? else { iFrames.load(function() { this.style.height = this.contentWindow.document.body.offsetHeight + 'px'; }); } }); Loading...
  45. Rod Permalink to comment# December 20, 2020

    It’s better to avoid using scrolling: it’s a deprecated attribute (see MDN: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#Deprecated_attributes)

    Loading... Reply

Leave a Reply Cancel reply

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

Comment *

Name *

Email *

Website

Save my name, email, and website in this browser for the next time I comment.

Copy and paste this code: micuno *

Leave this field empty

Δ

%d

Từ khóa » Html Iframe Resize To Fit Content