Centering elements with CSS

Posted Oct 13th, 2008 by David Calhoun in css

If you’re just starting out with CSS, you probably run into the problem of centering elements horizontally.  The common way to center an element within its parent container is by applying this:

margin: auto;

Or if you want to be more specific:

margin-right: auto;
margin-left: auto;

(which is the same as this:)

margin: 0 auto;

Still not centered?  Make sure the element is being displayed as a block:

display: block;

After all of this, is it still not centered?  Then you have to consider your browser itself.  Are you using a non-standard or outdated browser such as IE6 or older?  If you’re viewing on IE6, then there may be the possibility that your page is being rendered in quirks mode (especially if your webpage has no DOCTYPE tag), which renders the page using IE5.  In this case, you will need to add this to correctly center the element:

text-align: center;
Trackback URI | Comments RSS

Leave a Reply

Categories