Tutorial Categories:

HTML/CSS JavaScript/AJAX Server-Side Marketing General Comp-Sci

Centering Content Using CSS

By Justin Poirier

To center a fixed-width inline element in its containing element, the "text-align" CSS property should be used.

Fixed-width block-level elements, according to the CSS specification, are not affected by text-align and should be centered by setting their left and right margins to "auto". However, in IE versions 5 and under, IE versions 6 and 7 while in Quirks mode, and Netscape Navigator version 4, auto margins are not recognized. Incidentally, the text-align property is applied to block-level elements in these browsers even though it shouldn't be. So for these browsers block-level elements can be centered by setting text-align to "center" in the parent element. This should be combined with the technique of auto-margins in the element itself used for CSS-compliant browsers, to ensure the page always works. Note that setting the text-align to "center" in the parent element also by default changes it in the element itself, since it is inherited. Therefore it should be explicitly set to the desired value in the element itself. When the content being centered is multiple elements, setting their text-align and "margin" properties is often best achieved using a wrapper div, as in the following example code.

body {
text-align:center
}
div.wrapper {
text-align:left;
margin-left:auto;
margin-right:auto
}

A liquid-width element should be centered by setting its left and right margins to the percentage of the parent element's width you want to remain exposed on either side.