Leo Leo - 5 months ago 12
Javascript Question

HTML block element overflowing its parent

I'm encountering a weird (maybe not) behaviour that I want to avoid because the end result is a horrible user experience. To help you understand the problem I put together the code snippet below.



var counter;
var counterDisplay;
var intervalRef;

window.onload = function(){
console.log("loading");
counter = 11;
counterDisplay = document.getElementById("spCounter");

intervalRef = setInterval(tickHandler, 1000);
};

function tickHandler(){

counter--;
counterDisplay.innerHTML = counter.toString();


if(counter == 0){
stop();
return;
}
}

function stop(){
clearInterval(intervalRef);
document.getElementById("daddyLongLegs").style.display = "block";
}

html,body{
width:100%;
height:100%;
font-family:Arial;
font-size:16px;
}
.page-wrapper{
height:100%;
background-color:#eee;
}
.growing-element{
height:800px;
display:none;
margin: 100px 100px 0 100px;
background-color:#ddd;
}

<div class="page-wrapper">
<div class="container-element">

<!--This element's height never changes once the page has been rendered-->
<div>
The hidden child element below will magically appear in: <span id="spCounter">10</span> seconds
</div>

<!--This element's height changes anytime after the page has been loaded-->
<div id="daddyLongLegs" class="growing-element">
Now you see me...
</div>
</div>
</div>





The code snippet is pretty simple, all the javascript does is to display a child element (
#daddyLongLegs
) after ten seconds. Make the "problem" more visual colored the parent element (
div.container-element
) different to the child element.

Problem



Now, when the child element (
#daddyLongLegs
) is displayed after 10 seconds, it doesn't seem to "stretch" the parent element (
div.container-element
). This is not the behaviour I'd like to achieve. I would like the parent element to re-adjust its height when its contents change. However, it is important that the height of the parent element ALWAYS cover the whole document

Question



How can I make the parent readjust its height once the content has changed? Is there a pure css solution to this?

Answer

As described on MDN, you can use min-height attribute instead of height so whenever your <div>'s child rises, it will extend parent as well

so from my comment:

use min-height: 100% instead of height: 100% on your .page-wrapper