CSS Trick: Body Width
Posted on
What do you do when you want your page’s content centered, but everything floated at the same time,
such as when using a grid-based CSS framework like Blueprint or the 960 Grid System?
There are two ways to do this. The first is the margin:auto; method.
...
<body>
<div id='header'>
...
</div>
<div id='content'>
...
</div>
<div id='footer'>
...
</div>
</body>
body > * { width:960px; margin:auto; }
But what if you have several floated blocks that don’t take up the whole width? You could put everything
in another div, which is a very popular solution…
...
<body>
<div id='content'>
<div id='left-side-bar'>
...
</div>
<div id='content'>
...
</div>
<div id='right-side-bar'>
...
</div>
<div id='footer'>
...
</div>
</div>
</body>
#content { width:960px; margin:auto; }
… but then you have an extraneous tag that serves no purpose other than for styling. That doesn’t seem very semantic to me. So I played around and discovered this little trick:
body { width:960px; }
This centers everything on the page, with a width of 960px or whatever you set it to. Then you can just use this for your HTML:
...
<body>
<div id='left-side-bar'>
...
</div>
<div id='content'>
...
</div>
<div id='right-side-bar'>
...
</div>
<div id='footer'>
...
</div>
</body>
I’ve found this extremely helpful when using CSScaffold, a PHP driven CSS framework that includes a grid layout plugin. This seems to work across all browsers, even though I’m not sure it’s correct CSS. The only real problem I see is that you cannot have elements spanning the entire width of the browser window like you could before. They will only span to the width that you set. So if you want the background to your header or footer to cover the entire page width, I wouldn’t suggest this method. Otherwise, It works great.