I recently came across an unexpected behavior in my coding. I had set the min-height of the body
to be equal to the height of the viewport (100vh). Inside the body, there was a div
element with the class of "container" that I wanted to take up the entire height of the body (100%), ensuring it extended to at least the full height of the viewport. However, this did not happen as expected. The only way to achieve the desired result was to also set the height of both the html
and body
to 100%. What could be the technical reason behind this issue? Shouldn't the div naturally inherit the (min-)height of its parent?
You can view a codepen example with the expected behavior commented out in the CSS section.
*,
*::after,
*::before {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: #ddd;
min-height: 100vh;
}
.container {
background: #aaa;
max-width: 500px;
margin: 0 auto;
padding: 1rem;
min-height: 100%;
height: 100%;
}
/* Uncomment for the expected behaviour */
/*
html,
body {
height: 100%
}
*/
<div class="container">
<h1>Some generic title</h1>
<p>Some random paragraph</p>
</div>