CSS: navigation bar to expand to the whole page height

Matt picture Matt · Oct 20, 2009 · Viewed 8.7k times · Source

Im not too great at CSS but hopefully someone on here can help. I have the following mockup. (i have stripped out my content to make it easy to view)

<body>
   <div id="container">
     <div id="header"></div>
      <div id="body">
          <div id="navBar"></div>
          <div id="mainContent"></div>
      </div>
     <div id="footer"></div>
   </div>
</body>

my CSS is as follows:

html,
body {
   margin:0;
   padding:0;
   height:100%;
}
#container {
   min-height:100%;
   position:relative;
}
#header {
   background:#ff0;
   padding:10px;
}
#body {
   padding:10px;
   padding-bottom:60px;   /* Height of the footer */
}
#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:60px;   /* Height of the footer */
   background:#6cf;
}

now im unsure as to how to get the "navBar" to be the page height. I've tried adding height: 100% but that doesnt work.

Thanks, Matt

Answer

Gordon Gustafson picture Gordon Gustafson · Oct 20, 2009

Giving an element height: 100% will give it a height equal to that of its containing element, which in your case is #body. Since body in your example is only as big as it needs to be to hold its content, #navBar will be 100% of that height.

To fix this, you can make #container and #body height:100% to make them as tall as tho body tag, which takes up the whole page:

#container {
    height:100%
}
#body{
    height:100%;
}

In the interest of completeness, you could also set the top and bottom of #navBar:

position: absolute; 
top: 20px; 
bottom: 60px; /* height of footer */

To understand the difference, play around with This JS Fiddle. Mess around with the height and top, bottom, position properties to see how your changes affect the layout; just don't use both positioning methods at once!