Thursday, June 11, 2009

Center a Web Page Horizontally

It is easy to center a web page horizontally when you use the table based layout. There is an "align" attribute for the table tag. We just need to assign the value "center" to this attribute and the table as a container for your web page will be in the center. But as I mentioned in my earlier post, it is recommended to use the Div based with CSS layout. Then can we do the same thing to center a web page?

The answer is no. The "align" attribute for the div tag is deprecated and will not be supported by the newer browsers. But this is not the key reason. The key reason is that the "align" attribute means differently for the div tag. It specifies the alignment of the content inside the div element, not the div element itself. So we cannot use this attribute to center the div box as a container. What can we do then?

CSS is our friend. The easiest way to center a div box horizontally is to assign a width to the box and apply this style protery: "margin: 0 auto". The first value for the margin proterty is for the top and bottom margins. The second value is for the right and left margins. Also the doctype declaration must be HTML 4.01 strict or above. All these together will place your web page in the center. Not very hard, right?