Apr 23, 2012, by admin
A website leans 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 poorer with increased motion. And it’s not that peoples 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.