How to dynamically adjust an iframe’s height

Suppose you want to include a child iframe on your page. You’d like to resize the height of the child iframe so that it doesn’t show a scrollbar. That is, you want something that looks like this:

Dynamic i-frame height example

Here’s one way you can do it. First, make the iframe that you want to include. I made a file “child-frame.html” that looks like this:

<html>
<head> <title>Child frame</title> </head>
<body bgcolor=”#000000″>

<font color=”#ffffff”>
<p>Child frame.</p>
<p>Child frame.</p>
<p>Child frame.</p>
<p>Child frame.</p>
<p>Child frame.</p>
<p>Child frame.</p>
<p>Child frame.</p>
<p>Child frame.</p>
</font>

</body>
</html>

Now in the parent frame, you can make code like this:

<html>
<head> <title>Parent frame</title> </head>

<body onload=”resizeFrame(document.getElementById(‘childframe’))” bgcolor=”#cccccc”>

<script type=”text/javascript”>
// Firefox worked fine. Internet Explorer shows scrollbar because of frameborder
function resizeFrame(f) {
f.style.height = f.contentWindow.document.body.scrollHeight + “px”;
}
</script>

<p>Parent frame.</p>
<p>Parent frame.</p>
<p>Parent frame.</p>
<p>Parent frame.</p>

<p>
<iframe frameborder=0 border=0 src=”./child-frame.html” name=”childframe” id=”childframe”>
</iframe>
</p>

</body>
</html>

You can also see a live example of resizing an iframe height dynamically.

What does this code do? When the body of the parent frame loads, it looks up the document element “childframe” which corresponds to the iframe. Then the page calls a function resizeFrame(). The function sets the height of the frame to be the scrollHeight, which effectively removes the scrollbar.

The only tricky bit is the “frameborder=0 border=0” attributes on the frame. If you leave off the frameborder attribute, Internet Explorer will assume that the frame should have a nonzero border, but it won’t include the frame border in the value it returns for scrollHeight. The net effect is that IE will show a scrollbar unless you add “frameborder=0”.

It always annoys me to dive into cross-browser development when it feels like things should be standardized. Looks like it annoys other people too.

Anyway, feel free to rip on my code in the comments, but I was looking for a simple, working example of setting an iframe’s height so that the iframe wouldn’t have a scrollbar.

77 Responses to How to dynamically adjust an iframe’s height (Leave a comment)

  1. Nice idea, but there’s one slight flaw in it…what happens when the text gets resized at least one size larger?

  2. Why are we using iframes? I thought they were evil.

  3. Just for comparison – please show an AJAX example of this same effect.

    But with that current code – what would really add an interesting effect would be the ability for the visitor to manually resize it from the borders with their icons

  4. When my wife tried to log into GMail in IE the past two days it gives her a bizarro’ error. After spending half an hour trying to fix it, I instead switched gears and spent the next half an hour convincing her to switch to FireFox.

    I will need all of your prayers on this one, (the religion does not matter), as her switching to Firefox could save me many hours of work each year.

    Also Matt if you are able to comment. I once heard a rumor at Web Master World from someone that google does not like frames.

    Does the Googlebot crawl inside an iframe?

    Thanks!
    dk

  5. what if you used:

    f.style.height = f.contentWindow.document.body.offsetHeight + “px”;

    instead of:

    f.style.height = f.contentWindow.document.body.scrollHeight + “px”;

    i didn’t try it.

  6. Matt, you read my mind! I’ve got an online shop front I’ll be opening in the next few weeks that uses another site for order processing. I planned on sticking their site within an iframe of my site for handling orders, and this will be perfect for making the design flow with the height of the iframe. Thanks!

  7. Noone really likes iframes, but a frame is a frame. From a technical point of view, there should be no reason why a robot should not be able to crawl frames, so i think, yes it crawls the iFrame as well.

  8. Boo, hiss. iFrames are evil! Unless. . . you are telling us they aren’t evil. Now THAT would be some big news. SEOs would probably talk about it relentlessly the rest of the month. 😉

    Brent D. Payne

  9. Ah standards, now we’re talking a useful post that will really help the masses!! I wish more people would jump on the standards bandwagon as well, in more ways than just one. Which brings me to email standards and the email standards project http://www.email-standards.org .

    As a rather profiled Googler, perhaps you can do something about Gmail being one of the absolute worst in terms of following standards? Gmail has become too popular to ignore in newsletter mailouts etc., but it’s seriously holding back creativity too by being so popular yet not following most standards. The tests the ESP guys have run might really surprise you in showing how terrible Gmail support for standards is. Also, I know this won’t budge Google, but Yahoo! gets rating excellent for both webmail versions and have been quick to respond with even small updates 🙂 Hope you can do something to help here considering your lamenting standards in the post!

  10. Please note! This will only work if parent and child frame are on the same domain. I don’t think there is a way to do this with different domains without massively changing browser options.

  11. Resizing an iframe like this only works if the parent document and the iframe are in the same domain (more precisely, the scheme, hostname and port match).

    Otherwise the JavaScript code throws an exception: “Permission denied to get property HTMLDocument.body”

  12. How about div tags?? why cant we use one div inside the another div?

  13. @Sam I Am: HTML in email should not be supported, period. I’m *happy* that gMail buggers it up.

    But, why ARE we talking about iFrames? Not that I’m a huge xHTML fan (iframes are deprecated in xhtml), but the only reason to use iFrames these days is for programmatic purposes (hidden iframes) when you’re afraid of AJAX for some reason (performance?).

    Why *does* Google keeping pushing deprecated, antiquated technology on us? Does it just not matter? Are iFrames making a come back? Did I miss the memo?

    🙂 Thanks for the great blog, Mr. Cutts.

  14. i use IE to test the page, the iframe do not have any change when i resize the parent frame.

  15. Does the resizing also work when you embed a page via iframe that lives on a different host?

  16. [quote]Otherwise the JavaScript code throws an exception: “Permission denied to get property HTMLDocument.body”[/quote]

    In this case you could use “scrollable” divs instead of iframes.

  17. Ah the fun of standards 🙂 standards polatics makes real elections seem tame like a vicars tea party.

    I remeber that one (now defunct) computer manafacturer decided to ingnore an OSI standard that said counter must start from 1 and started it at 0 – cue nasty divide by 0 errors.

    And Sprint totaly Ignored bits of certain OSI standards and every one else had to put in hacks to interoperate with there MTA’s

    search engines web

    but ajax would not work for search engines 🙂 unless the google bot has been enhanced 🙂 BTW Matt any idea if the google bot will eaver be able to read java script and ajax pages ?

  18. Nice, but I wish there was something for a IFraming a different domain.

  19. Did you just use a tag and define style inline? For shame! A strong wag of the finger sir!

    🙂

  20. sorry that was <font> tag

  21. Good tip but like Geiger, I am still looking how to dynamically resize the iframe for an external domain.

  22. Rip on your code? Why, looks good, it works, ship it! 🙂
    One thing I might add though is that the iframe content MIGHT not be known at parent window load time. But if the content of the iframe is small and server response is good, it usually isn’t a problem. Also, that works well the first time an iframe is loaded and loaded on parent load but if it is switched at some point, the iframe won’t resize. But, that shouldn’t happen unless someone is foolish enough to use iframes for navigation! :-()

    But, if late loading does become a problem, the way around it is to put the iframe content size detection in an onload in the iframe content and then have that call the parent’s resize bit. Of course the problem with that is then the parent is dependent on the child supporting it although tests for it, and from the iframe side, can easily be made for a more bombproof implementation.

    One problem I see though that might be more serious, whether to use document.body or document.documentElement depends on whether a doctype is used or not so I think that your code could use some further bombproofing.

    As for “standards” seemingly not being standard, it used to get on my nerves too when I’d get a killer layout or script working in one browser only to find it totally borked in another and IE is NOT the only problem.

    But, over the years I have found that after getting something working across “all” browsers, I always ended up with a more solid implementation and now after learning most of the workarounds, or things to avoid in some cases, that various browsers need to get it to look the way I want, doing things in a cross browser fashion from the beginning has almost become second nature.

    I definitely enjoyed your getting “down and dirty” with the code jockeys amongst us and hope you do more as you have time and opportunity. 🙂

  23. Omar Yesid Mariño

    Yes, it is annoying. Sometimes cross-browser development is really delayed due to the non-standardized things. Maybe Google need to release its own browser. 🙂

  24. I should have read the other comments before commenting myself…

    Dr. David Klein, if Google is given clear links to the content in the iframe, either through the iframe’s src attribute or through navigation in the parent which uses the target attribute, Google has no problems crawling the contents of iframes.

    But, a site using iFrames for navigation will have problems because the contents of the iframes essentially becomes a PageRank black hole. On a normal page, one would have site and content navigation on each “page” but if the contents of the page is iframed and the navigation is in the parent, the iframe content would have to duplicate the navigation of the parent for PageRank to flow from that page back to the rest of the site and that would get ugly fast.

    Add to that, someone trying to link to iframed content has to know what they are doing to get the link to the actual content they want to link to and not just the URL of the parent. If they don’t get it right, that page loses the link love it might have gotten and ends up with a lesser amount.

    Add to that, if someone does link to the contents directly, what happens when someone follows that link or Google indexes that page? Unless one takes measures to prevent it, usually using Javascript, one following a link to iframed content will end up at the content with no support site frame around it.

    Add to that, problems with bookmarking and it gets more depressing.

    Personally, I’ve found it easier to make an AJAX navigated site more user and search engine friendly than an iframe navigated site.

    Of course there are those who would ask the obvious question, “Why do either?” But sometimes one has to do what one has to do. 😉

  25. As much as I despise using iframes, it seems there always comes a time where it may be the only solution – even if temporary. And the issue with never being able to dynamically adjust the height was dreadful. Thanks for the tip Matt!

  26. Matt – Thanks, I am trying to do iframes on my website(s) as a form of compliant crosslinking while at the same time displaying my product(s) in the sidebars. I noticed Google throwing the beatdown on crosslinks in my blog sidebars that appeared sitewide so an iframe appeared to be a solution, correct? You know my website Matt (where I sell my product), take a look if you like. I will send you the link of my other related site where I have it linked in an iframe on the sidebar, is it compliant?

    Can you talk a bit about “iframes and crosslinking” we really need a solution out here, I want to show my product on related sites but only want to pass one link credit or none at all/if not related with a nofollow from the sidebar, thinking too much?

    Thanks will cut and paste/test your code later, was annoyed with that scrollbar in IE, so very ugly…

    One more: It gets a little sad out here as a webmaster when you do things that might be seen as spamming search engines, 99% of the time this is not the intent, there is just no information anywhere on this stuff and I am still not sure I am not breaking any algorithmic rules…grrr.

    Got to run, 12 inches of fresh snow to shovel in the north east, weee!! 🙂

  27. Thanks for this Matt. Now we can all expect Neil Patel to get REAL crazy while embedding his YouTube profile onto other websites.

  28. font tags and bgcolor attributes, oh my!

  29. Browser developers want to have a standard too, it just so happens that everyone dreams about their own version being the standard. It is gonna be a long way. When FF takes 40-50% of market share, maybe webmasters can collectively force one to stop re-inventing the wheel!

  30. No meta descriptions? I suppose these are not for Google’s index, nor its SERPs?

  31. iframe = the Devil

    Suggestion – use div class with css property ‘overflow:scroll;’. Also, correct me if I’m wrong but is our aim here to create an iframe that dynamically resizes, and we’re stfu on standards, so why not just use AJAX?

  32. i-frames? I thought i-frames were a large no-no for optimization and user accessability?

    i personally really dislike the use of i-frames, especially when they have scrollbars….i-frames in my opinion should be a last resort solution when developing a user interface.

    I look forward to other opinions on i-framing here….but from a majority of colleagues of mine, i-framing = bad idea

  33. i-frames are sometimes used by link spammers to fake a frame pagerank as the whole page pr. and this is cheating other webmasters

  34. Good Idea, the div + css design can dynamically adjust an iframe’s height too.

  35. Matt,

    I came across something interesting today with regards to IFRAMES, and its pretty scary, especially what I have seen it do….

    I dont want to post it here, because if I did, it could well open the flood gates and cause more havoc than I can imagine on the internet.

    Plus you would probably be really peeved if I did, as it could well do things to your blog that you would not like…. I tried it on my blog, and it did stuff I didnt like….

    Do you have a email addy I can send you the info to, so you can test it out, maybe have see who will be affected and get google to have a word in the ear of the major providers that are affected, as little old me wont be able to handle it all 😉

    I could be over-reacting, but I dont think I am, this appears to be a nasty little hack, that certainly affected my wordpress blog, some custom stuff I had, and no doubt will affect some other software, which could lead to serious havoc on the net.

  36. Cross-browser compatibility: The bane of web designers. Why CAN’T they standardize???

    And Matt, thanks for your help a while back with my site, you helped fix things right up, whether through your advice or attention. 🙂

    Vic

  37. Sam I Am, if I run into any Gmail people, I’ll mention it.

  38. Kevin, I’m glad if it helps. n@3k is right though: I think that this only works if the iframe is on the same domain as the parent though. 🙁

  39. “Did you just use a tag and define style inline? For shame! A strong wag of the finger sir!”

    Seth, I’m a bad Googler. 🙂

  40. “No meta descriptions? I suppose these are not for Google’s index, nor its SERPs?”

    Gab “SEO ROI” Goldenberg, I’ve been helping a nonprofit put a calendar on their site (Google Calendar on the backend, PHP iCalendar on the frontend), so I was working within some constraints. I went looking for a dead-simple “how to” and all the people talking about it were giving code fragments but not the complete page. So I just wanted to write up a minimal example so that other people could see one way to do it.

    I appreciate everyone not ripping *too* hard on the code. 🙂

  41. Dave (original)

    I think that this only works if the iframe is on the same domain as the parent though.

    Contact Rogers the Candian ISP, they manage it 🙂

  42. In defense of iframes, I find them to be very useful, want a few examples?

    Say I do a book review and want to link over to Amazon.com to earn a few pennies, you can insert an iframe widget directly in the content with an image of the book, price, sale price ect. This allows you to not clutter your content with over-monetization and is VERY search engine compliant.

    The same goes for placing items you sell on multiple sites without suffering the wrath of excessive crosslinking in Google.

    Iframes are the future, I am using them today! 🙂

  43. As far as I know, there is no way to do it for an external page.
    It would be a security issue if possible.

  44. Come on guys, iFrames have their place sometimes.

    Here are two sites (disclaimer: my own sites) using iFrames to do what you otherwise could not:

    http://webwait.com – measures web page load times by checking how long it takes to load in an embedded iFrame.
    http://weborandom.com – shows random web pages in iFrames that you can navigate through

    As the sites are external, though, it’s unfortunately not possible to use Matt’s hacks due to the browsers’ cross-site security model. I had an idea for a site a while ago (which would have served an extremely useful purpose), but played around with many options, and it was apparently impossible by any means for the outer frame to discover the height of the inner frame’s body, if they come from different domains.

  45. Sure you can. Take a look at how the guys do it over at Google Custom Search Business Edition. They create an iframe, that sets its parent (window.top) location to include a fragment for the window’s document.body.scrollHeight. Neat!

  46. I find it amusing that frames are being discussed and there are discussions about the wrong things. Saying iframes are evil is silly. Ajax is good?

    Please.

    http://en.wikipedia.org/wiki/Anthropomorphism

    No amount of what you technically will ever save you if what you are saying is not useful or relevant. Personally I rarely visit here because I do not spam search engines and Matt you are after all the head of the Web Spam team.

    I’ve said enough.

  47. And, of course, Google itself uses iframes all the time to embed AdSense ads.

  48. Waitwaitwaitwaitwaitwaitwait…there’s something much more important going on here that no one’s talking about: Matt is getting his web design freak on! GETCHU SOME!

    This is going to be really interesting…how long before Matt turns the tables and starts asking the rest of us a million questions? He’s got some chits coming. 😀

    Seriously, dude, what’s the not-for-profit?

  49. You have to think for yourself and test, test, test. There are lots of legit reasons to use iframes. I use them on client sites to place forms on pages that I’m trying to optimize when the form is bloated with code. If done right the user doesn’t know the difference and the engines don’t have to crawl through 200 lines of bad code to crawl a page.

    Blindly saying, “I thought iframes were evil…” just shows why good SEOs are hard to come by. Too much time reading blogs and forums and not enough time actually working and testing.

  50. First of all the protocall you would want to use to achieve Matts desired outcome would be AHAH (Asynchronous Html And Http) not AJAX (Asynchronous Javascript And XML). AHAH allows you to dynamically grab html from another url and combine them together into a single document. The new document can now be formatted using a standard css.

    Here is an example of AHAHLIB.js

    function callAHAH(url, pageElement, callMessage) {
    document.getElementById(pageElement)
    .innerHTML = callMessage;
    try {
    req = new XMLHttpRequest(); /* e.g. Firefox */
    } catch(e) {
    try {
    req = new ActiveXObject(“Msxml2.XMLHTTP”);
    /* some versions IE */
    } catch (e) {
    try {
    req = new ActiveXObject(“Microsoft.XMLHTTP”);
    /* some versions IE */
    } catch (E) {
    req = false;
    }
    }
    }
    req.onreadystatechange
    ➥ = function() {responseAHAH(pageElement);};
    req.open(“GET”,url,true);
    req.send(null);
    }
    function responseAHAH(pageElement) {
    var output = ‘’;
    if(req.readyState == 4) {
    if(req.status == 200) {
    output = req.responseText;
    document.getElementById(pageElement)
    .innerHTML = output;
    }
    }
    }

    once the data has been returned standard DOM methods can be utilized to insert the response into the document object of choice and a css can assign formatting to it.

    Just an idea. Hope it helps.

  51. great solution. Even if i don’t usually use iframes i think this script works really fine. Thanks.

  52. thanks for the tip, I was actually having some issues with similar code, and this fixed it

  53. Thank you very much, it is much more elegant this way instead of setting height to 1000 px 😀

  54. Hello Matt,

    Thanks for the tip, I was searching for this for very long time I could not get rid of either the huge space below the content of my page either the ugly scroll down bar…

    Now the big mystery… is iframe content crawled by Google?

  55. iFrames are often quite handy, and get the job done better than any other simple method.

    people who say “who ajax instead”, i’d love to. can you provide a simplified iFrame replacement in AJAX?

    i’m very interested in learning more about AHAH now. hoping to find a simple iFrame replacement in AHAH. not sure how to implement the AHAH example given above.

  56. cross-domain auto-sizing iFrame solution:

    (requires ability to put script into remote page)
    http://www.surveygizmo.com/forum?forum=3&topic=836

  57. Thx that works fine !

    The problem in IE with scrollbars its fixed if you add a little amount of pixels. Ex:

    function resizeFrame(f) {
    var size;
    size = f.contentWindow.document.body.scrollHeight+10;
    f.style.height = size + “px”;
    }

  58. saved certain minutes matty

  59. I’ve been in arguments with fellow developers about this one at times, some feel iframes are evil 100%, but I’ve always felt they’ve had their use. A few commenters on here pointed out great examples of good iframe use. If you’re using iframes for text content, you can probably use other techniques to get the same effect without the seo drawbacks of iframes, but certain applications just make sense to use an iframe.

    Kinda like when people go through the trouble of trying to make crazy tables with div tags that should probably have just been HTML tables in the first place, blindly thinking that all html tables are evil.

  60. First of all, a big thanks for your time and sharing.

    I’ve tried to use your original code, but i had two small problems:

    one, i did not want to use body onload.

    second, it worked fine while retriving the first page. But if i linked from the framed page to another, smaller one, the height remained the same.

    Well, some reserching and i’ve came up with this:

    // Firefox worked fine. Internet Explorer shows scrollbar because of frameborder
    function resizeFrame(f) {
    var s;
    s = 100;
    f.style.height = s;
    s = f.contentWindow.document.body.scrollHeight + “px”;
    f.style.height = s;
    }

    a) putting the onload to the iframe, the iframe re-configures the height everytime the iframe loads. Also, b) putting the f.style.height to change twice, the iframe has always the correct height, even if i go from a bigger to a smaller linked page.

    It works for me in ie v7, ff v3.0.7 and Chrome.

    Hope it comes in handy,

    Thanks again for sharing,
    Giannis.

  61. I’ve been using IFRAMES and tables all my life. It’s the best option when you refuse to (or can’t) use PHP, ASP or any other dynamic db-based designs.

    Thanks a lot for this code, it’s exactly what I needed. Glad to know someone else uses IFRAMES.

    Cheers from Argentina.

  62. Retro Iframes 🙂 well sometimes its saves time …. 🙂

  63. Thanks for posting it. I did something very similar and wish I found it a week earlier.

    The problem mentioned above about the loading order is significant. You have to do the onload event on the iframe document and not on the parent. The iframe can load after the parent.

    Why iframes? Many good reasons. Forms in popups without heavy duty javascript support. It is also a lot easier to build popups with forms and other modal interactive functionality with iframes instead of ajax.

    If you want a quick and snappy website, all the gimmicks are out the door. Think web 2.0 in terms of the user experience, not in terms of how you write code.

    Say what you want about google, they are giving user what they want. User first, code second. This means in many ways iframes first ajax second.

    This really has nothing to do with SEO. Googlebot does not fill forms and upload photos.

  64. I have used this code but height is not extend. could you please advise me?

    // Firefox worked fine. Internet Explorer shows scrollbar because of frameborder
    function resizeFrame(f) {
    f.style.height = f.contentWindow.document.body.scrollHeight + “px”;
    }

  65. Sorry for commenting on such an old topic, but using a very similar solution I got the impression that Firefox bases the scrollHeight value on the size of the content _before_ applying the CSS style, giving a sometimes very inaccurate results. IE seems fine though.

    Somehow I haven’t found annyone mentioning it so far. I’m still investigating this, accuracy not guaranteed.

  66. I also tried this
    function resizeFrame(f) {
    f.style.height = f.contentWindow.document.body.scrollHeight + “px”;
    }
    but height is not extend

  67. Thanks for sharing.
    The script only work for the same domain. You guys complain code doesn’t work most probably is because your iframes try to reach other domain. Browser stop cross-site javascript access.

  68. Possible solution for cross domain iFrame height problem.
    ———————————————————

    jQuery(document).ready(function($) {
    resizeWindow();
    function resizeWindow() {
    var height = $(window).height();
    $(“#iFrameRapper”).height(height);
    };
    var resizeTimer = null;
    $(window).bind(‘resize’, function() {
    if (resizeTimer) clearTimeout(resizeTimer);
    resizeTimer = setTimeout(resizeWindow, 100);
    });
    });

    html, body
    {
    overflow: auto;
    }

  69. I’ve tested it and crossbrowser solution that works for me is like that:

    Function:

    function resizeFrame(f) {

    var size;
    size = f.contentWindow.document.body.scrollHeight + 10;
    f.style.height = size + "px";
    }

    And iframe call:

    document.write('');

    Thanks to: mattcutts for the topic 🙂 and Giannis for onload idea

    • what do you mean by : ” And iframe call: document.write(”); ”

      can you explain better what to put exactly.. I could use the extra help..

      This is what I’m using:

      // Firefox worked fine. Internet Explorer shows scrollbar because of frameborder
      function resizeFrame(f) {
      var s;
      s = 100;
      f.style.height = s;
      s = f.contentWindow.document.body.scrollHeight + "px";
      f.style.height = s;
      }


      Back to MY SITE

      PLEASE HELP?!! anyone???

  70. This was the simplest solution I have seen so far on this subject. Worked like a charm. Couple of things I noticed: May need to change the quotes if you are copying and pasting from this post. There is no ‘border’ attribute for an iframe only frameborder. dont forget to set your width on the child iframe:

  71. works in IE7, doesn’t seem to work in FireFox (FF) 3.0.19

  72. Possible solution to the cross domain resize issue is to cname the other domain, then link it to the cname so that the initial page load is happening on your own domain.

    This type of solution is nice for someone that is using external proprietary forms to generate mortgage or insurance quotes, and does not have the source code for the form they’re using, but the subscribing company will allow a cname reference to their server.

  73. Im applying almost the same method to resize the iframe dynamically in my web page templatesrule.com/web-templates/template-demo-3207.html but its not effecting dont know why. any idea?

  74. Loren Helgeson

    Interesting solution. I like what you’ve done here, but I gotta ask. What’s wrong with “frameborder=0” in the code? Frameborder, as an HTML atrribute, validates. The “border” property, when used with an iframe, does not.

  75. Very nice solution. I tried others, but this was the only one that worked for me.

  76. using IE9, this did not work for me. This is what I used in the parent page.

    function resizeFrame(f) {
    f.style.height = f.contentWindow.document.body.scrollHeight + “px”;
    }

css.php