How to dynamically adjust an iframe’s height

January 13, 2008

in How to, Weblog/blog

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.

{ 63 comments… read them below or add one }

Multi-Worded Adam January 13, 2008 at 10:20 pm

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

Dane January 13, 2008 at 10:41 pm

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

Search◊ Engines Web January 13, 2008 at 10:43 pm

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

Dr. David Klein (purposeinc) January 13, 2008 at 10:59 pm

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

arlo January 13, 2008 at 11:14 pm

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.

Kevin January 13, 2008 at 11:42 pm

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!

Matthias January 13, 2008 at 11:59 pm

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.

Brent D. Payne January 14, 2008 at 12:43 am

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

Sam I Am January 14, 2008 at 12:59 am

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!

n@3k January 14, 2008 at 1:42 am

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.

Klaus Johannes Rusch January 14, 2008 at 2:04 am

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”

webtechnepal January 14, 2008 at 2:10 am

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

Allan Haggett January 14, 2008 at 2:40 am

@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.

John January 14, 2008 at 2:56 am

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

yaph January 14, 2008 at 3:59 am

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

collector January 14, 2008 at 5:04 am

[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.

Maurice January 14, 2008 at 5:09 am

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 ?

Geiger January 14, 2008 at 5:30 am

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

Seth January 14, 2008 at 5:56 am

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

:)

Seth January 14, 2008 at 5:56 am

sorry that was <font> tag

VaBeachKevin January 14, 2008 at 6:20 am

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

Craig January 14, 2008 at 6:44 am

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. :-)

Omar Yesid Mariño January 14, 2008 at 6:45 am

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. :-)

Craig January 14, 2008 at 7:02 am

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. ;-)

Ben Rabicoff January 14, 2008 at 7:28 am

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!

Aaron Pratt January 14, 2008 at 8:36 am

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!! :)

Tanner Christensen January 14, 2008 at 8:49 am

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

chris January 14, 2008 at 9:09 am

font tags and bgcolor attributes, oh my!

Hart January 14, 2008 at 10:44 am

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!

Gab "SEO ROI" Goldenberg January 14, 2008 at 12:37 pm

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

Aaron January 14, 2008 at 1:48 pm

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?

web design fort myers January 14, 2008 at 1:54 pm

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

Wedding Dres January 14, 2008 at 5:07 pm

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

piaoyi January 14, 2008 at 5:35 pm

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

ken January 14, 2008 at 7:43 pm

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.

ScreenRant.com January 14, 2008 at 8:40 pm

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

Matt Cutts January 14, 2008 at 9:43 pm

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

Matt Cutts January 14, 2008 at 9:45 pm

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. :(

Matt Cutts January 14, 2008 at 9:49 pm

“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. :)

Matt Cutts January 14, 2008 at 9:52 pm

“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. :)

Dave (original) January 14, 2008 at 9:56 pm

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 :)

Aaron Pratt January 15, 2008 at 7:47 am

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! :)

Black Hat Domainer January 15, 2008 at 12:50 pm

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

Michael Mahemoff January 15, 2008 at 3:46 pm

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.

biggav January 15, 2008 at 9:31 pm

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!

Dan Nedelko January 16, 2008 at 12:43 am

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.

Eric Giguere January 16, 2008 at 5:34 am

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

Multi-Worded Adam January 17, 2008 at 11:05 pm

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. :D

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

Aaron January 18, 2008 at 1:47 pm

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.

Frederick Gimino January 19, 2008 at 8:44 pm

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.

Paolo January 22, 2008 at 1:38 am

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

Allen January 22, 2008 at 9:14 am

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

Varadi Peter January 26, 2008 at 7:19 pm

Thank you very much, it is much more elegant this way instead of setting height to 1000 px :D

Emmanuel January 28, 2008 at 3:34 pm

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?

johny February 1, 2008 at 12:01 pm

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.

johny February 9, 2008 at 5:27 am

cross-domain auto-sizing iFrame solution:

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

Ryu July 22, 2008 at 2:25 am

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”;
}

Lokimona July 27, 2008 at 6:07 am

saved certain minutes matty

Luke August 25, 2008 at 11:34 am

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.

Giannis March 18, 2009 at 7:04 am

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.

Cristian April 25, 2009 at 12:45 am

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.

webdesign June 19, 2009 at 3:43 am

Retro Iframes :) well sometimes its saves time …. :)

HTML September 26, 2009 at 12:25 am

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.

Leave a Comment

If you have a question about your site specifically or a general question about search, your best bet is to post in our Webmaster Help Forum linked from http://google.com/webmasters

If you comment, please use your personal name, not your business name. Business names can sound salesy or spammy, and I would like to try people leaving their actual name instead.

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Previous post: Data portability for your email, searches, calendar, …

Next post: Formatting USB hard drives for Ubuntu (Gutsy Gibbon)