There are two commonly used methods of setting up a centered main wrapper (or container) div element on your website. Usually, a web page will reside in one big div, sitting just inside the body tags, like so:
1 2 3 4 5 6 7 8 | <html> <head><title>My Site</title></head> <body> <div id="container"> ... </div> </body> </html> |
This basic structure makes it easier to control the page’s layout. By far, the most prevalent method for styling the container looks a bit like the following:
1 2 3 4 5 6 7 8 9 | body { text-align: center; } #container { margin: 0 auto; text-align: left; width: 960px; } |
In line 6, the container div’s left and right margins are set to auto and its width set to 960 pixels. This is the basis for centering the div on the page. There is another approach, which I found a bit cooler until just recently.
1 2 3 4 5 6 | #container { left: 50%; margin-left: -480px; position: absolute; width: 960px; } |
This method doesn’t require giving text-align:center to body and then overriding it immediately in the container div. I like that.
However, a complication arrises when you want to put a background image at the bottom of body; for example, a horizontal gradient. In this case, the best cross-browser way I’ve found to work is the first container centering method (using margin:0 auto). In addition, the html and body tags will require some additional styling to make it happen:
1 2 3 4 5 6 7 8 9 | html { height: auto !important; min-height: 100%; } * html {height:100%} /* IE6 */ body { background: url(/images/bg-footer.png) repeat-x bottom; } |
The body style is obvious, but it’s important to manage the height of the parent html element as well, remembering of course that IE6 does not support min-height. Incidentally, it’s also IE6 that is responsible for the text-align:center that we applied to body.
In conclusion, don’t use the absolutely-positioned approach for styling your container. It’s cooler, but it just isn’t as robust as the standard auto-margin method because it breaks out of the page layout (specifically, its html parent). For adding any background image to the bottom, now or in the future, that is bad behavior. Stick margin:0 auto on your container and be done with it.
