Go Back to Dynamic Site Solutions :: CSS

Centering Block Level Elements

This <p> is absolutely positioned 50% from the left side of body. It has a negative left margin of half of its width. In this case, when I say width I am referring to the total calculated width of this element. Except in IE's faulty box model, this includes the left and right padding, the left and right borders and the specified width of the element. This method does not work in IE4 or NS4. The second method is better than this first method because with this method if the browser is less wide than the width of the element, the element's content that is off the left edge of the viewport won't be accessible.

This <p> has auto left and right margins as well as a width specified which centers it in CSS2 browsers. It will not work if the width is not specified or if this element is floated or absolutely positioned. Its parent element has text-align:center; to compensate for IE incorrectly applying text-align to block level elements instead of requiring the use of auto left and right margins. Block level elements are 100% of the available width by default, so I did not need to specify the width on the <div> that contains this paragraph. When IE6 is in standards compliant mode it handles centering correctly. To put IE6 in standards mode use a doctype with an URL. Any characters other than white space characters before the doctype will put IE6 back into IE5 compatibility mode. For example, adding the XML declaration before the doctype in XHTML pages will cause this bug.

This paragraph (<p>) does not have a set width. The left and right margins are set to specified widths instead. These 3 examples are slightly misaligned in Netscape 6 because of the vertical scrollbar. The wrapper div compensates for the scrollbar in the other browsers.

This paragraph (<p>) and it's parent element, which in this case is a <div>, both have position:relative set. It's parent has left:50% set and it has left:-50% set. Neither element needs a set width when using this technique. If the inner element has a set width, then it needs to be the same as its parent's. The inner element can have borders, padding, and/or margins defined, however, the outer element can't.

Related Links:

Last update: 2006-08-21