Centring with CSS

In the old days of old, before CSS, XHTML and XML came along, plonking a table in the middle of a page was easy as adding align=”center” into the table tag.

...

But now, while it will still work, this method has been depreciated in favour of using CSS (Cascading Style Sheets), and simply adding a small bit of code will not centre an item like a table. While you can use text-align on some things, it will not centralise everything as it only works on inline content, and not block content like a table or a DIV.

So, how do we do it? Well, it is still quite simple, just not as straight forward – we have to define the width of the object, and then set the left and right margins to auto:

.tableclassname {
width: 400px;
margin-left: auto;
margin-right: auto;
}

That will centre an object in Firefox (and its close relations), but not in Internet Explorer. To support IE, we have to do one more small thing, which is to add text-align: center; to a CSS style for the body element.

body {
text-align: center;
}

That should now make sure things align centrally in IE, but now you will notice that all the text in tables and DIVs are now centred as well. Annoying, isn’t it?

So, all we do now is to use text-align: left; where it is needed – this should work in all (or most) CSS capable browsers.