Centering Block-Level Elements In CSS
Posted April 30, 2007on:
If you’ve written much CSS, then you probably know that the different implementations of the CSS rules by each rendering engine are really frustrating. Firefox, Opera, IE5, IE6, IE7, Safari, and more all seem to have different interpretations of how your code should look. They make no exception with the use of different rules that allow you to center objects.
Some common ways are to use margin: 0 auto; on a block level element, and using text-align: center; on the parent of an inline element. Well, the auto sides setting on the margin rule doesn’t always act like it should, and you might not want all of your actual text centered. So here’s a better solution, albeit a bit more strict in it’s implementation:
Okay so what’s going on here? With the left rule we’re forcing the left side of the object to be in the exact center of the screen. Since it’s then going to be too far to the right, we use the margin-left rule to bring it back by half of the width of the object. Obviously, this doesn’t work too well with dynamically sized objects, which is why I mentioned that it’s a bit strict; however, I think it’s an excellent way of getting around browser inconsistencies regarding margin: 0 auto;.