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

<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.

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

To center #page, you need the following CSS:

body {
	text-align:center;
}
#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.

Scroll to Top