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.

"Seamless" Iframe

HTML5 introduces a seamless iframe attribute which is not yet supported in a meaningful way by any browsers. This code, as well as the Hidden Iframe code, provides some of the features that will be provided by the seamless attribute once it is supported. The JavaScript provided here allows the iframe to expand to the height needed to display all the content without iframe scrollbars, as shown in the example.

Links in the document inside the iframe open inside the iframe by default, but you can include target attributes to point to the parent document as described in Loading New Documents in Iframes. The styles in the parent document are not inherited by the iframe's document. Styles to be applied to the content in an iframe need to be included in that document. This handling of styles and links contrasts with the Hidden Iframes code and example where links open in the main window and the parent document styles are inherited by the iframe's content.

The Code

The JavaScript to set iframe height to match its document's height consists of a getDocHeight function that obtains the height of the document, cross-browser for both standards and quirks mode documents, and a setIframeHeight function that sets the iframe element's height to match the contained document's height. 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>

These functions are displayed and included in the example as well as in the download file.

Back to top