iFrame height to content with no scroll bars

I've seen allot of developers requesting the ability to resize a iFrame so that the content in the iFrame fits in the frame without any scroll bars, but also to adjust the height dynamically so that is always fits the height of the internal content, which is useful for iFrames who's content changes often or when using iFrames in a site that is responsive and adapts to the browser it is loading in.

There are many examples of doing this on the internet, but unfortunately most of these examples only work in old browsers, new browsers have many restrictions for the interest of security and now new methods are required to perform the requirements.

Below is my solution to this problem, which works on all modern browsers using event listeners to pass information between the parent and child frame in the browser. Follow the instructions below to implement the solution into your project, which works in FireFox, Chrome, IE and Safari (and perhaps all others).

Note: You will need to include the jQuery library for this code to work.


Step 1

Place the following code in the parent document (the document that will include the iFrame) and change #myIframe to the ID of the iFrame you want to resize.

window.addEventListener('message', function(e) {
var $iframe = jQuery("#myIframe");
var eventName = e.data[0];
var data = e.data[1];
switch(eventName) {
case 'setHeight':
}, false);


Step 2

Place the following codeĀ into theĀ page that will included as an iFrame:

function resize() {
var height = document.getElementsByTagName("html")[0].scrollHeight;
window.parent.postMessage(["setHeight", height], "*");

//window resize
$( window ).resize(function() {
var height = document.getElementsByTagName("html")[0].scrollHeight;
window.parent.postMessage(["setHeight", height], "*");
$( window ).trigger("resize");

You should now have a self resizing iFrame.


Step 3 (Optional)

For better results, disable iframe scrolling and remove the horrible default border for a lighter, sleeker one:

<iframe src="#" style="width:100%;border:1px solid #561010;overflow:none" scrolling="no"></iframe>


Author: Dean WilliamsI'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips

Post Tags:
, , ,
0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments