October 17, 2012
Vertical centering hack
You might have noticed that by default, the label on a <button> tag is centered vertically in all browsers. I was curious how each browser achieves this, so I did a little digging.
Firefox and Webkit browsers appear to use CSS3 flexbox, which makes sense for modern browsers. IE8 and below is a different story. What’s odd is that the code that centers the label is somehow hidden from the inspector. It’s as if there is no CSS property that affects the vertical alignment, yet the label is still centered vertically.
I figured somebody must have an explanation for this, so I headed to twitter:
@peterhry: What intrinsic CSS property allows the content inside a <button> to be centered vertically?
After a short exchange with @simurai, I concluded that IE must have some magical built-in centering mechanism.
The beautiful thing about this, is that you can put anything inside the button tag: images, divs, whatever… it gets centered. And this works in every browser. The only thing you need to do is add this CSS:
This removes the native button styling in all browsers while leaving the vertical centering intact.
Admittedly, this technique is a bit dirty and I wouldn’t recommend using it for all your vertical centering needs, but it could be handy for styling menus or other things that actually warrant the use of a button tag.
“NASA is planning a mission to Mars. Meanwhile, we’re trying to vertically center elements with CSS.”