Reputation: 45
I encountered what for me is an unexpected behaviour. I wanted to set the body
min-height to the height of the viewport (100vh), then make a div
(with the class of container) inside it that would take the whole height of the body (100%), so that the div would extend at least to all of the height of the viewport. Except that this doesn't happen; the only way to achieve this result is to set html
and body
height to 100%. What's the technical reason that makes this this happen? Shouldn't the div take the (min-)height of 100% of its parent anyway?
Here you can find a codepen with the expected behaviour commented out at the end of the css
*,
*::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>
Upvotes: 3
Views: 10348
Reputation: 410
this does the magic for me. the idea is min-height is 100vh or 100% in case content is larger than 100vh.
body {
background: gray;
height: max-content;
min-height: 100vh;
display: flex;
flex-direction: column;
}
.container {
background: silver;
margin: 0 20px;
flex-grow: 1;
}
Upvotes: 1
Reputation: 179
*,
*::after,
*::before {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: #ddd;
min-height: 100vh;
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>
Upvotes: 0
Reputation: 78686
The answer is simple as percentage min-height
is calculated based on parent container's height
value not min-height
.
* {margin:0;}
body {
background: gray;
height: 100vh; /* look here */
}
.container {
background: silver;
margin: 0 20px;
min-height: 100%; /* look here */
}
<div class="container">
<h1>Some generic title</h1>
<p>Some random paragraph</p>
</div>
But, with min-height:inherit
it then inherits the min-height
value from the parent container.
* {margin:0;}
body {
background: gray;
min-height: 100vh; /* look here */
}
.container {
background: silver;
margin: 0 20px;
min-height: inherit; /* look here */
}
<div class="container">
<h1>Some generic title</h1>
<p>Some random paragraph</p>
</div>
I would set min-height:100%
on .container
directly if it always covers the viewport height.
* {margin:0;}
body {
background: gray;
}
.container {
background: silver;
margin: 0 20px;
min-height: 100vh; /* look here */
}
<div class="container">
<h1>Some generic title</h1>
<p>Some random paragraph</p>
</div>
Upvotes: 10