CSS View Height is Causing IFrame To Constantly Resize

Viewed 29

I have this weird issue where the CSS property vh (height of the viewport), is causing my iframe to grow exponentially in size. To start, inside my iframe code is the following:

function sendPost() {         
                
                setInterval(function(){

                    try {
  

                        let adjust_height = document.body.offsetHeight || document.body.clientHeight;

                        parent.postMessage( JSON.stringify({ command: 'adjust_height', height: adjust_height}), '*');
                      
                    } catch(e) {
                        console.error(e);
                    }

                }, 3000);
}

To summarize, every 3 seconnds, I am sending to the IFrame parent the new height of the content inside the frame, and then IFrame then resizes its height to fit the new content without scrolling. Works great! Example if I add in something like like:

#mainContainer {
   min-height: 75vh;
}

And the HTML inside the IFrame can simply be:

<html>
   <body>
       <div id="mainContainer"></div>
    </body>
</html>

Now this causes the mainContainer to constantly grow. For example:

//1st Interval Height is 500
let adjust_height = document.body.offsetHeight || document.body.clientHeight;

/2nd Interval Height is 700
let adjust_height = document.body.offsetHeight || document.body.clientHeight;

//3rd Interval Height is 900
let adjust_height = document.body.offsetHeight || document.body.clientHeight;

When I uncheck the VH css property, the height stops growing. Why is VH changing the document height inside an Iframe?

1 Answers

vh is a relative size, see: CSS values and units

The definition of 1vh is 1% of the viewport's height. It's important to note that for an iframe the iframe itself is the viewport.

So in your case the content of your iframe gets bigger, the parent adjusts the size of the iframe, which means that 75vh will get bigger, which starts the vicious circle.

See also: Viewport concepts

Related