Arieh.co.il

Full height body

The problem

OK - this is something every developer comes to tackle at least a few times a year, and it is never simple - how do i make the body expand to exactly the height of the window, no matter the window size, without javascript?

Oh, this is simple - you might say - just give the body height 100%. Go ahead - try it. Lets take this markup and CSS:

The actualy example is here.
<!DOCTYPE HTML>
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<title>Body Won't Expand</title>
    <style type="text/css">
        body{height:100%}
        #top,#bottom{width:100px; height:100px; background:#0cd;}
        #top{top:0}
        #bottom{bottom:0;}
    </style>
</head>
<body>
	<div id="top"></div>
	<div id="bottom"></div>
</body>
</html>

What happened? Well, you see - although you give the body 100%, it actualy only expands as far as it's children make it. This is actualy a very big headache, and the solution isn't generic.

The solution

The solution takes 4 steps.

  1. The first is to remember that the body is not the root element of our document - the html is. So the first thing we need to do is to give it height:100%
  2. The second is to give our body height:auto
  3. The 3rd is that we need to give our body a min-height of 100% - min-height:100%. Don't ask me why, but for most browsers, this does all the trick.
  4. For IE 6, that doesn't have min-height, we need to hack one. We do this by adding a height:100% at the end of the statement, and add !important to the height:auto statement.

This would look like this:

html{height:100%}
body{
    min-height:100%;
    height:auto !important;
    height:100%;
}

I actualy don't like this solution. Using !important is a bad habit, and can be harmful on the long run. But since we don't usualy style the body, it is a compramize I'm willing to take.

Links

  1. I've found the solution here, but it adds some extra markup that i found unncessary (realy- i'm not sure why it's there).
JavaScript Reference, JavaScript Guide, JavaScript API, JS API, JS Guide, JS Reference, Learn JS, JS Documentation