October 17, 2012

Vertical centering hack

Vertical centering on the web has always been a pain. Unfortunately CSS doesn’t offer a simple (and well supported) way to center elements vertically. There are techniques that work but most have drawbacks. Some depend on extra markup or JavaScript, some require you to hard code the height of the element being centred, etc. Here are a few popular approaches.

It turns out though, there is yet another way to achieve vertical centering. It’s cross-browser compatible and so stupidly simple you probably won’t believe it at first. It requires no extra markup, no JavaScript, and almost no CSS. What? That’s right, almost no CSS.

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:

background: none;
border: none;
padding: 0;

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.”