Dynamically Resizing iFrame

In case you have an iFrame which serves content of unknown size to your main page, you can use JavaScript to read the actual size of the iFrame's height relative to its content and alters the iFrame container's size. Then your iframe will be dynamic and can change its size automatically.

Prerequisites

CSS

An additional div element is needed to be double sure overlapping of the iframe on the main page does not occur and to make sure the area is correctly collapsed, if Browser size changes.

Security

The solution will not work cross-domain. Your Browser does not like XSS. Neither will you, if your cookie gets stolen in a client-side attack and you get impersonated. Well over 80% of all security problems are cross-site scripting related.

In case you absolutely must have cross domain compatibility you could try Cowboy's jquery-postmessage.

Implementation

JavaScript

In this example we will try to read out the iFrame's content height and change the iFrame's height accordingly to it. To accomplish this, put this code inside the head element of your main document:

That should do the trick. In case you found this helpful you could backlink to this article.

Thank you for reading!