Setting Iframe Height to Match Content Height

On this page we present JavaScript that sets the height of an iframe to match the height of its content so that regular window scrollbars are used instead of iframe scrollbars. An example demonstrates.

The JavaScript consists of two functions: getDocHeight and setIframeHeight. They both do what their names indicate: getDocHeight obtains the height of the document in the iframe, and setIframeHeight sets the iframe element's height to match the document height obtained. A call to the function setIframeHeight is added to the iframe element's onload attribute:

<iframe id="ifrm" src="pages/height1.html" onload="setIframeHeight(this.id)"></iframe>

The Functions

There is no standard way of obtaining the height of a document, so the getDocHeight function checks a variety of properties to determine which contains the largest value[1]:

function getDocHeight(doc) {
    doc = doc || document;
    // stackoverflow.com/questions/1145850/
    var body = doc.body, html = doc.documentElement;
    var height = Math.max( body.scrollHeight, body.offsetHeight, 
        html.clientHeight, html.scrollHeight, html.offsetHeight );
    return height;
}

The setIframeHeight function obtains references to the iframe and the document inside it as described in Accessing an Iframe and its Document and Content:

function setIframeHeight(id) {
    var ifrm = document.getElementById(id);
    var doc = ifrm.contentDocument? ifrm.contentDocument: 
        ifrm.contentWindow.document;
    ifrm.style.visibility = 'hidden';
    ifrm.style.height = "10px"; // reset to minimal height ...
    // IE opt. for bing/msn needs a bit added or scrollbar appears
    ifrm.style.height = getDocHeight( doc ) + 4 + "px";
    ifrm.style.visibility = 'visible';
}

Demonstration, Download, and More

An example demonstrates the JavaScript presented here. It is included in a download file along with the other tutorial examples. See the rest of the Iframes Tutorial which includes much more information on iframes and how they are used.


  1. The algorithm for calculating document height is from StackOverflow. ^