CSS Div stretch 100% page height

Tom picture Tom · Apr 3, 2009 · Viewed 366.8k times · Source

I have a navigation bar on the left hand side of my page, and I want it to stretch to 100% of the page height. Not just the height of the viewport, but including the areas hidden until you scroll. I don't want to use javascript to accomplish this.

Can it be done in HTML/CSS?

Answer

Knyri picture Knyri · May 17, 2012

Here is the solution I finally came up with when using a div as a container for a dynamic background.

  • Remove the z-index for non-background uses.
  • Remove left or right for a full height column.
  • Remove top or bottom for a full width row.

EDIT 1: CSS below has been edited because it did not show correctly in FF and Chrome. moved position:relative to be on the HTML and set the body to height:100% instead of min-height:100%.

EDIT 2: Added extra comments to CSS. Added some more instructions above.

The CSS:

html{
    min-height:100%;/* make sure it is at least as tall as the viewport */
    position:relative;
}
body{
    height:100%; /* force the BODY element to match the height of the HTML element */
}
#cloud-container{
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    overflow:hidden;
    z-index:-1; /* Remove this line if it's not going to be a background! */
}

The html:

<!doctype html>
<html>
<body>
    <div id="cloud-container"></div>
</body>
</html>

Why?

html{min-height:100%;position:relative;}

Without this the cloud-container DIV is removed from the HTML's layout context. position: relative ensures that the DIV remains inside the HTML box when it is drawn so that bottom:0 refers to the bottom of the HTML box. You can also use height:100% on the cloud-container as it now refers to the height of the HTML tag and not the viewport.