Stickers
Stickers

Reputation: 78686

Horizontally center align block element

I think lots of people like me keep doing it like this:

html {
    text-align: center;
}

body {
    margin: 0 auto;
    width: 80%;
    text-align: left;
}

http://jsfiddle.net/ofpy7mgz/

I don't even remember why we add text-align: center; to the parent element, must be for browser compatibility? Well, is it safe to simply drop that now days?

Edit: The goal is just for center aligning <body> element, not for any text alignment etc.

Upvotes: 0

Views: 452

Answers (2)

pavel
pavel

Reputation: 27092

It was because IE6 (and the older ones + I think IE7 in quirk mode) centered all elements (both block and inline) by this way, margin: auto didn't work there.

Other browsers (non-IE) wasn't able to center block elements by text-align: center;. They used, as a specification said, text-align: center for inline elements, margin: auto for block elements.

You can remove that if you don't want to support IE6.

Upvotes: 2

Giacomo Alessandroni
Giacomo Alessandroni

Reputation: 696

If you would like use your code, more simply:

body {
    margin: 0 auto;
    width: 80%;
    text-align: center;
}
<p>hello world.</p>

Upvotes: 0

Related Questions