How to center a website in CSS

A lot of websites that we build require the site to be centered regardless of the total screen width. I remember in the days of tables we’d simple put a master table of 100% width on the page, add a TD with an align=’center’ tag then nest another table inside to centre the main content.

With CSS the principle doesn’t have to be too different but the code is a lot neater. Here’s how I usually do it:

1) Create two CSS divs, one for the master container and one for the content:

div#container
{
 margin: 0 auto;
 background-color:#fff;
 width:600px;
}
div#content
{
 padding:20px;
}

The margin:0 auto; is the important part here. That is what will center the content within. The background-color and width attributes of the container div and padding attribute of the content div are just to highlight the example, you can remove these or change them to suit your design.

2) In your HTML, add your divs into the page BODY:

<body>
 <div id="container">
  <div id="content">
   Hello World!
  </div>
 </div>  
</body>

And that’s it!

Here’s the full code:

<html>
<head>
<style>
body
{
 background-color:#000;
}
div#container
{
 margin: 0 auto;
 background-color:#fff;
 width:600px;
}
div#content
{
 padding:20px;
}
</style>
</head>
<body>
 <div id="container">
  <div id="content">
   Hello World!
  </div>
 </div>  
</body>
</html>