Center Align the DIV

By Akbar

As I discussed in my previous thread, more and more people and moving toward the Tableless design to design the HTML files. Check the following post for detail:

A Step toward Tableless Design

Of course, the migration is not as simple as it looks. Designing the page layout with just the DIVs (basically not using tables) is not that easy for newbies. There are many tricks and tweaks you learn with time (similar to what it was with table based design). One question I asked frequently is that how you can center align the DIV tag using the stylesheet. The reason for this the trick to do this using CSS is not that intutive. You may start with “text-align:center”, or by doing “float:left”, but all this doesn’t work. The correct way to do this using something like this:

<div style="margin:0 auto;width:930px;">
	Center Aligned Box
</div>

In the width, you can give it either by percentage (to make it relative to current page width) or in pixel (hard coded). There is still one small catch. Sometime you will notice that it doesn’t work in the IE. The most probable reason is that IE is running in the Quirks Mode 🙂

To fix this, add the following line which set the DOCTYPE to restrict:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

Hope it helps.

Tags: