Centering a page with HTML and CSS

Posted in HTML and CSS -

This post looks at how to center the layout of a page in a web browser, so that it is initially centered and if the user resizes their browser it will remain centered. It is very easy to do using HTML and CSS with only a minor issue in older versions of Internet Explorer to deal with.

The basic skeleton would look this:


    <div id="container">
        ... other divs and content here ...


#container {
    width: 900px;
    margin: auto;

Obviously you can set the width of the container to whatever you want it to be, 900px is just an example. All your other divs would then sit inside the container div.

This works in all versions of Firefox from 1.0 up (it may work in the earlier versions but that's the earliest I have on my browser test machine) and Opera 7.0 up (ditto Firefox comment). With Internet Explorer it will work with both Internet Explorer 6 and Internet Explorer 7 as long as a doctype has been specified. The above example doesn't include a doctype but as long as you include one then it will work in those versions of Internet Explorer.

In older versions of Internet Explorer, you need to add an additional declaration to the stylesheet. The modified version of the style sheet would then look like this, with the changes in bold:

body {
    text-align: center;
#container {
    width: 900px;
    margin: auto;
    text-align: left;

Adding text-align: center; to the style sheet makes everything centered in IE. However it will also make text in all other divs etc align to the center, so we fix this by adding text-align: left; to the container div. This will now allow the container to be centered for older versions of Internet Explorer (prior to IE 6.0) and also center the container in IE6 and IE7 if no doctype is specified.

Related posts: