HTML - Iframe Element (nested browsing context) (inline frame)


The iframe element.

nested browsing context


<iframe sandbox="allow-same-origin allow-forms allow-scripts" src=""></iframe>


  • The default height is the default height of the html element which is 150px

Why is there a margin between the body and html element for the document inside the iframe

The padding of the first descendant phrasing element (such as p or pre but not div) are added to the HTML element in a iframe context.


<p style="padding:10px">A div with a padding that will be propagated to the HTML element</p>


Get the content of an iframe as a document

// Note that iframe.contentDocument == iframe.contentWindow.document

Get the parent document


Javascript Snippet

Set the height of the iframe to the height of its window after loading to avoid overflow

This demo updates the height of the iframe to the height of the internal window.

This example is just for demonstration purpose because you can also achieve the same with the height css attribute, namely.

window.addEventListener("load", function () {

    // Select the iframe element with the class webCode
    const webCodeIFrames = document.querySelectorAll("iframe.webcode-combo");

    // Set the height of the iframe to be the height of the internal iframe
    if (webCodeIFrames != null) {
        for (let i = 0; i < webCodeIFrames.length; i++) {
            const webCodeIFrame = webCodeIFrames[i];
            const height = webCodeIFrame.getAttribute('height');
            if (height == null) {
                let htmlIFrameElement = webCodeIFrame.contentWindow.document.querySelector("html");
                let calculatedHeight = htmlIFrameElement.offsetHeight;
                let defaultHtmlElementHeight = 150;
                if (calculatedHeight === defaultHtmlElementHeight) {
                    // body and not html because html has a default minimal height of 150
                    calculatedHeight = webCodeIFrame.contentWindow.document.querySelector("body").offsetHeight;
                    // After setting the height, there is a recalculation and the padding of a descendant phrasing content element
                    // may ends up in the html element. The below code corrects that
                    requestAnimationFrame(function() {
                        if (calculatedHeight !== htmlIFrameElement.offsetHeight) {
                            webCodeIFrame.height = htmlIFrameElement.offsetHeight;
                webCodeIFrame.height = calculatedHeight;


Documentation / Reference

Powered by ComboStrap