Centering a Website – Cross Browser

Most sites these days are centred and have a fixed with be it 800, 1024 pixels wide or whatever.  If any of you have used divs and css and tried using standard centering you might have, at one stage or another, scratched your head while viewing it on different browsers.

Let’s say we want a webpage with a width of a nice round 1000 pixels. To do this we might create a new div within the body tag called page:

<body>
<div class="page">Content goes here<br/><br/><br/><br/><br/></div>
</body>

In order to centre this on IE7 and less we simply set the width in the div and in the body tag set text-align to center i.e.

body
{
 text-align: center;
}
.page
{
 width: 1000px;
 text-align: center; /*don't forget to reset alignment for child elements*/

}

On IE8+, Firefox and other browsers this is not correct behaviour however and they will left align the inner div, therefore we need to centre the inner div using the margin tag by setting it to margin: 0 auto e.g.

body
{
 text-align: center;

}
.page
{
 margin: 0 auto;
 text-align: left;
 width: 1000px;
 background-color:red;

}

By specifiying margin: 0 auto and by setting the div’s width, the browser can calculate how much distance to place between the left side of the div and the left margin of the browser window.

So there you have it, simple and effective and cross browser compatible.

One thought on “Centering a Website – Cross Browser

Leave a Reply

Your email address will not be published. Required fields are marked *