A website tends to look more balanced when it’s centered on the monitor, instead of clinging to the left side with lots of white space on the right. This looks even worse with increased resolution. And it’s not that folks will use that white space to make notes…..
So to center your page, wrap your content into a container – a ‘wrapper’ of sorts. Like so:
<body> <div id="wrapper"> <div id="content"> <p>This is where your entire content would go: - header, navigation, footer, whatever. It would likely be in different divisions, but for this demonstration, we do not need those details.</p> </div> (this closes the 'content' division) </div> (this closes your 'wrapper' div) </body> </html>
And now we use two simple lines in the CSS to move things to the middle:
First, we need to give our wrapper a width:
#wrapper { width: 980px; }
How wide you set this wrapper, of course depends on your design. Instead of pixel, you could use %, or even em, but pixel is probably the better choice.
And here comes the magic wand:
#wrapper { width: 980px; margin: 0 auto; }
And voila – a perfectly centered website! What did it is the line:
margin: 0 auto;
It tells the browser to put a margin of zero to the top and bottom of the wrapper division (of course you can adjust that to your liking) and to automatically figure the right and left margins to center the wrapper (that needs to stay ‘auto’ for the centering to work).
P.S. – In the olden – aka pre-IE6 days, this needed to be done by adding a
body {text-align: center;}
and then, to neutralize all that, a
#wrapper {text-align: left;}
But thank goodness, those days are gone. It’s been ok to NOT support anything less than IE6 for a long time now, and even IE6 is about to be extinct.
This post was written by: Andrea BarnettThis entry was posted on Friday, February 19th, 2010 at 4:59 pm and is filed under CSS Basics, CSS Page Layouts, Killer CSS Tips and Tricks. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.



Very useful hints ,
TNX
i’m using ie7, i notice that without the doc type declaration the auto centering does not work. does it center in all browsers once you declare the doc type, incuding ie 6 or lower?
The doctype is part of a properly coded website – it needs to be there. And yes, this centers in all current browsers including IE6 – for IE5, things had to be done differently, but that old version no longer requires support.