Friday, March 20, 2009

Horizontal Centering With CSS

I was doing some research about how to center page elements (both vertically and horizontally), and thought I'd share my findings here. I couldn't find anything about centering elements vertically, but there are actually two ways to go about centering elements horizontally using CSS, and only one is IE5 compatible.

Centering: Negative Margin
First, position the element's left edge at the horizontal center of the page using "position:absolute; left:50%;". Then, set the box's left margin is to the opposite of half the element's width using "margin-left:-266px;". Like this:

body {margin:0px; padding:0px;}

#Content {
position:absolute;
left:50%;
margin-left:-266px;
}

Centering: Auto-width margins
The other way is to center the element by setting left & right margin widths to "auto". This CSS is not supported in IE5, however. To remedy this, [kind of], we can use the "text-align" attribute. IE5 incorrectly applies the CSS "text-align" attribute to block-level elements. Declaring "text-align:center" for the containing block-level element (often the BODY element) horizontally centers the box in IE5. There is a side effect of this workaround: the CSS "text-align" attribute centers the inline content. when centering in this way, you should explicitly set the "text-align" attribute for the centered box, counteracting the effects of this crappy way to center things. Honestly, just use the other way. Code as follows:

body {
margin:50px 0px; padding:0px;
text-align:center;
}

#Content {
width:500px;
margin:0px auto;
text-align:left;
}

No comments:

Post a Comment