Webpage Workshop: Home » CSS » How to center a page

How to center a page

A centered CSS layoutIn this tutorial you will learn how to create a single column page layout that is horizontally centered on the page (see the diagram to the left for an example of the desired effect). There are two techniques that are commonly used to achieve this effect; auto-width margins, and the negative margin method.

The most commonly used of the two techniques, and the simplest to comprehend, is the auto-width margin method, and so we shall discuss that method first.

Auto-width margins

This is the easiest of the two methods, but is unfortunately not directly supported by Internet Explorer. Never fear though, as there is a workaround built into this method in order to achive the effect in the Microsoft browser.

It works by secifying the width of the central column of the page (in pixels or as a percentage) and by setting the margins of the column to an automatic value. In order to deal with the shortcomings of Internet Explorer, it is necessary to introduce a text-align: center; property to the body element. This, however, results in all of the text on the page also being centered, and so a text-align: left; is added to the CSS for the centered column.

body {
    margin: 50px 0px;
    padding: 0px;
    text-align: center;
}

div#main {
    width: 600px;
    margin: 0px auto;
    text-align: left;
    padding: 15px;
    border: 1px solid #000000;
    background-color: #eeeeee;
}

In the above code, one division is used to contain the main text of the page and is given id="main" as an attribute.

Negative margin

This method is less common, but works nevertheless. It relies on positioning the main division 50% across the page so the left side is in the center, and then changing the left margin to a negative value equal to the sum of half the width of the division, the thickness of the left padding of the division, and the thickness of the border on the left side (confusing eh?).

body {
    margin: 0px;
    padding: 0px;
}

div#main {
    position: absolute;
    left: 50%;
    width: 600px;
    margin-top: 50px;
    margin-left: -316px;
    padding: 15px;
    border: 1px solid #000000;
    background-color: #eeeeee;
}

In the above example, the main division is absolutely positioned 50% across the page, and then the left margin is set to -316px, ie. -((width/2) + left padding + left border) = -((600/2) + 15 + 1) = -316