Centering Text with CSS

One of the most common requirements in web page layout is to horizontally center images or blocks of text on a web page.

The old html way of doing this was to use the center tag or the align attribute.

<center>center this</center>
or
<p align='center'>center this</p>

As we are supposed to separate Content from Presentation we shouldn't use an html tag or attribute to do this.

So how do we recreate this effect using only CSS?

To center a block element, say a paragraph tag, correctly using CSS we need to set the left and right margins properties to auto and the text-align property to center.

p {margin:auto;text-align:center;} /* the right way to do it*/

Adding a width and a border to the style centers the block as shown in the heading at the top of the page.

p {margin:auto;text-align:center;width:70%;border:1px solid red;} /* the right way to do it*/

Unfortunately the answer is complicated because of a bug in Internet Explorer.
However the bug does disappears if you force IE6 into compliance mode by adding a DOCTYPE. Which of course you always do, don't you ?. It is another good reason to build correctly constructed web pages.