Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Div height: 100% not working with body min-height: 100vh

Tags:

html

css

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>
like image 565
mpasquato Avatar asked Dec 08 '25 15:12

mpasquato


2 Answers

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>
like image 156
Stickers Avatar answered Dec 10 '25 04:12

Stickers


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;
}

like image 33
Felipe Rodriguez Herrera Avatar answered Dec 10 '25 04:12

Felipe Rodriguez Herrera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!