Centre Horizontal

The content of a div on your page can be centred horizontally by setting margins to auto like this:

#box {width:400px; margin: 0 auto;}

Unfortunately, Internet Explorer 5 on Windows does not recognise this way of centring the content of a div and so the content doesn't get centred in that browser (even older browsers don't understand it either but hardly anyone is using those older browsers). There are still a significant but slowly falling number of web visitors who use IE5 so it is preferable if we can use code that will horizontally centre the content for them as well.

As well as not understanding the standard way of centring content, IE5 also incorrectly applies the text-align attribute to block level elements. We can make use of this to centre our div by using the following code:

body {text-align:center;}
#box {width:400px; margin: 0 auto; text-align:left;}

Of course our page content to be centred will look like this:

<div id="box">
This content is centred

This sample page shows you what some full page horizontally centred content looks like in your browser. I have added some padding, a border, and more text so that you get a better idea of how it works.

If your div is to be centre aligned within another div rather than in the whole page then just add the text-align:center to the id for that div instead of to the body.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow