Centering a Web Page with CSS

One of the most commonly asked CSS questions is "How can I use CSS to center a web page?" This is a useful technique to know if you are creating a fixed-width web page but you want it to be shown in the center of the user's browser rather than down the left-hand side.

There is no in-built CSS or HTML command to do this, so we need to get creative with our <div> tags. Firstly we have to set up a container (or "wrapper") <div> that we can use to surround all of our content. We will give this a fixed width and then set its left and right margins to auto. When we do this, the browser will automatically make the left and right margins the same width and hey presto, our page content should appear in the center!

First the HTML:

<div id="container">
All of our page content, including our headers,
menus and content sections, go inside the container div.
</div>

Now the CSS:

#container {
	width: 600px;
	margin: 0 auto;
}

So is that all there is to it?! Well... no, not quite. Although this technique should and indeed does work perfectly in most web browsers, Internet Explorer has problems displaying it properly, so we need to do a quick fix to get around it.

What we need to do is to center all our content within the body section by applying the following CSS:

body {
	text-align: center;
}

We should now see that our content is indeed shown in the middle of the page, but now we have another problem - all the text and images within our web page are also centered. In order to move them back to the left we need to apply left text-alignment to our container <div> like so:

#container {
	width: 600px;
	margin: 0 auto;
	text-align: left;
}

There, that wasn't so hard was it? This is a simple solution that will work in any web browser.