CSS Horizontal Centering Hack

February 12, 2007 by hejian

The correct way to horizontally center any element is to use the margin property and set left and right values to auto:

div#content {
margin-left: auto;
margin-right: auto;
}

This works in some browsers, but not in others. Another means of centering is to use the text-align property for a given element, which in many browsers will align the element as well as the text:

div#content {
text-align: center;
}

Because neither the correct way nor the text-align method works in all browsers, you’ll want to combine the technique:

div#content {
margin-left: auto;
margin-right: auto;
text-align: center;
}

And this creates your horizontal center hack. Of course, because you now ask that all text be aligned within the element, you’ll have to be sure to create rules that overwrite that:

div#content p {
text-align: left;
}

This makes sure that any paragraph within the now-centered content division will align properly.

Leave a Reply

You must be logged in to post a comment.

Wordpress template made by HeJian