Setting Iframe Height to Match Content Height

This portion of the Iframes Tutorial provides information and JavaScript for setting 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

The JavaScript to set iframe height to match its document's height 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"

There is no standard way of obtaining the height of a document, so a variety of properties are checked to determine which contains the largest value.[1]

function getDocHeight(doc) {
    doc = doc || document;
    var body = doc.body, html = doc.documentElement;
    var height = Math.max( body.scrollHeight, body.offsetHeight, 
        html.clientHeight, html.scrollHeight, html.offsetHeight );
    return height;

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

Demonstration and Download

See these functions in action in this example. It is available in a download file, along with the other Iframes Tutorial examples.

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