CSS, Stretching vertically div until it reach the height of its parent

Very Curious picture Very Curious · Aug 6, 2013 · Viewed 41.5k times · Source

Wrapped in a pageWrapper container, I have 3 divs in a column. First (header) and last (navWrapper) have fixed heights. I need the middle one (contentWrapper) to stretch in height until the parent div pageWrapper reaches the maximum height (according to the browser's viewport).

I draw the schema of this problem. enter image description here

Here is a fiddle of my current solution. http://jsfiddle.net/xp6tG/

and here the code

CSS and HTML

html, body{
  height: 100%;
}

body{
  background-color: #E3E3E3;
}

#pageWrapper{
  margin: 0 auto;
  position: relative;
  width: 600px;
  height: 100%;
}

header{ 
  display:block;
  width: 100%;
  height: 100px;
  background: yellow;
}

#contentWrapper{
  width: 100%;
  height: 100%;
  background: blue;
}

#navWrapper{
  width: 100%;
  height: 100px;
  background: green;
}
<div id="pageWrapper">
  <header>
    Header
  </header>
  <div id="contentWrapper">
    Content
  </div>
  <div id="navWrapper">
    Nav
  </div>
</div>

It is almost working, but it results in too high height, which causes that a vertical scrollbar appears.

Answer

Marc Audet picture Marc Audet · Aug 6, 2013

Here is one way of doing it.

Apply the following CSS:

html, body{ height: 100%; margin: 0;}
body{ background-color: #e3e3e3;}

#pagewrapper{
    margin: 0 auto;
    position: relative;
    width: 600px;
    height: 100%;
}
header{ 
    display:block;
    width: 100%;
    height: 100px;
    background: yellow;
}
#contentwrapper{
    width: 100%;
    position: absolute;
    top: 100px;
    bottom: 100px;
    left: 0;
    background: blue;
}
#navwrapper{
    width: 100%;
    position: absolute;
    height: 100px;
    bottom: 0px;
    left: 0;
    background: green;
}

Since you specified heights for the header and #navwrapper block elements, you can use absolute positioning with respect to the parent #pagewrapper block to set the bottom and top offsets for #contentwrapper and the bottom offset for #navwrapper.

If you see a scroll bar, you may need to set margin: 0 for either the html and/or body tags.

Demo fiddle: http://jsfiddle.net/audetwebdesign/yUs6r/