I ran across a pretty wicked-cool article on Smashing Magazine late last night, and decided to do a little experimenting.
It turns out (even though NONE of the browser vendors have addressed this issue) there’s actually a way to vertically center elements.
Distilled, the CSS is pretty simple:
top: 0; left: 0; bottom: 0; right: 0;
We all know the
margin: auto trick for horizontal centering, but if you combine
position: absolute, and set the
bottom properties to 0, guess what? It’s worky for vertical centering as well!
Stephen Shaw’s article goes on to show that it works in most scenarios, including padding, offsets, and even responsive resizing.
I gave it a little run in CodePen, specifically wanting to see what happens when the absolute centering is inside of a container, and you move that container around. The results of my experimentation are here:
Sure enough, the vertical centering stays true to the CSS rules around position:absolute (If the containing element is relative or fixed, positioning — and in this, case centering — is relative to the bounds of the container). As you can see from the screenshot, in addition to the immovable, centered
div (with a nested centered
div inside of it), there are two fanciful elements, with all their fancy dragging abilities. Each draggable element has double nested, vertically centered
In short, it works like a charm.
I did, however, make one modification for text, and that is to treat the
div containing text with
The reason for this is so that we can vertically center multi-line and single-line text. If we employ the vertical centering CSS, like Stephen did, to a div with text, the text won’t ‘cheat up’ on multiple lines. The fix for this is pretty straightforward:
[Update: the height is automatically calculated, so no reason to set it, unless you maybe want to look at compatibility/fallback -- Thanks Stephen!]
You’ll notice the
height property is set to
2.4em. Setting the height to this value is a good approximation for the amount of height needed when you have a multi-line text
If you want to display a single line in the center, just add the following:
Feel free to play around with the CodePen example, and do make sure to check out Stephen Shaw’s article.
He did the heavy lifting here, I’m just propagating a great code snippet.
See the Pen here
Or snag the Gist right here