6

I'm trying to make a container fill the entire page (or the viewport, whichever is larger), but ran into some trouble. I'm using the recommendations from this post: https://stackoverflow.com/a/17555766, to set the <html> and <body> to 100% height.

But I've noticed that the .Content div only fills the viewport when the <body> height is set with height: 100%, but not with min-height: 100%. Why is that? Why doesn't .Content pick up the height of the <body> when it's set with min-height? Is there a fix for this (without absolute positioning or fixed heights)?

html

<html>
  <body>
  <div class="Content">Content</div>
  </body>
</html>

css

* {
  margin: 0;
  padding: 0;
}

html {
  height: 100%;
}

body {
  /* does not work for .Content: */
  min-height: 100%;
  /* does work for .Content: */
  /* height: 100%; */
  background: blue;
}

.Content {
  background: red;
  min-height: 100%;
}

codepen: http://codepen.io/anon/pen/mJEMVX

P.s.: when the <body> height is set with height: 100%, both min-height: 100% and height: 100% work as expected for .Content.

Community
  • 1
  • 1
  • 2
    I guess the underlying reason is the circular dependency between the body height and the content height. Imagine there's another element after the `.content`. Now, if the content expands to 100%, the body must expand too, which would cause the content to expand further. Probably the reason why the spec defines a percentage height the way it does is to break this circular dependency. – Alexey Lebedev May 18 '15 at 08:08
  • @Alexey Lebedev: That is correct. – BoltClock May 18 '15 at 08:08

1 Answers1

6

Percentage heights refer to the computed height property of the parent element. See the spec. When setting only min-height: 100% on the body element as per my answer to the linked question, the height property is left untouched at its default value of auto. The min-height property does not affect the computed value of the height property.

Because of this, min-height: 100% on your element does not have a parent height to refer to, and so it won't work. Once you set height: 100% on the body element, your element is able to refer to this height for its own percentage height calculation.

How to fix this depends on what sort of layout you're trying to achieve. The only purpose of setting min-height: 100% on the body element is to allow it to expand when the content height exceeds that of the viewport resulting in a scrollbar. If your content will only ever be exactly the height of the viewport, or you don't want body to generate scrollbars, it's as simple as replacing min-height: 100% with height: 100% on body.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356