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[1] 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 is brief and includes just two functions. The getDocHeight function obtains the height of the document, cross-browser for both standards and quirks mode documents. The setIframeHeight function 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.
Dont' forget: An error of access denied or permission denied will be triggered if you try to use JavaScript to access the document loaded into the iframe if it is from another domain. Find out more about JavaScript's same origin policy.
- Find out more about the HTML5 Iframe Element's seamless attribute specification. ^