Correct (CSS) way to center a page element in HTML

by Yang Yang on January 6, 2009

<center></center> as well as the property align=”center” used to be the tag that centers everything inside. However, it’s not the right way to do the centering in HTML at all. Let me show you the correct way in CSS to center something on the page.

Let’s say you have a page wrapper that wraps a whole page which you need centered in the browser.

	<div id="page">
		div#page is centered.

To center #page, you need the following CSS:

body {
#page {
	margin:0 auto;
	width:990px; /*Without a width smaller than 100%, div is 100% in width by default and expands to the parent borders*/
	text-align:left; /*As text-align property is automatically inherited, you need to reset it so that the texts and other elements inside div#page are not put in the center.*/

If you need more elements inside #page to be centered, just remove text-align:left because text-align:center on body is automatically inherited to all its children.

Comments on this entry are closed.

Previous post:

Next post: