New(?) way to center elements verticaly.
Maybe new, maybe not, I don't know but I haven't seen it anywhere.
This technique is based on two inline-block elements with vertical-align set to middle. First one have set 100% height and second one is where we put content.
HTML:
<i class="inliner"></i>
<div>Sample content</div>
CSS:
.inliner {
height: 100%;
}
.inliner,
.inliner + * {
display: inline-block;
vertical-align: middle;
}
You can play with it here: http://jsbin.com/oxuyop/919/edit
Written by Kasper Mikiewicz
Related protips
16 Responses

Great tip! Doesn't seem to work in IE7 tho..

nice once :D

@emilnordh I was thinking the same thing. Thanks for trying out.

@emilnordh What about IE8?

And given we're not supporting IE7 (don't know about IE8, either, though, but should work)... here's the obligatory no-extra-markup version: http://jsbin.com/oxuyop/102/edit

@nathansmonk It works in IE8+ and any browser that support display: inline-block;
@passcod looks good tought you will be able to center only one element in page. With mine code you can center anything ;)

@idered No no no... you can center anything too. I'm just using the body
element as a container. Replace body:before
with parentelement:before
and everything still just works (see: http://jsbin.com/oxuyop/144/edit). After all, it uses the exact same technique... just without extra markup.

@passcod :before and :after isn't supported i IE7 either. @idered I think IE7 supports inline-block on elements wich are usually used as inline?

@emilnordh Nope, it doesn't support it at all. Usualy *display: inline; is used as fallback for IE7 but in this case it doesn't work.

I first ran across this tip at http://css-tricks.com/centering-in-the-unknown/ , and he references http://gtwebdev.com/workshop/vcenter/vcenter-inline-css.php . Doesn't matter if others already have it though, it's a great tip!

@emilnordh IE7 = .87% users. Screw them. :)
Btw great tip. Thanks so much.

@nathansmonk IE8 don't work

You can do this with a single element using :before pseudo-element: http://bl.ocks.org/2867324, it avoids the extra DOM element.

I already tried this without using * selector
https://coderwall.com/p/bjovyw?i=5&p=1&q=&t%5B%5D=%21%21mine&t%5B%5D=%21%21bookmarks
With IE7 you may have to force haslayout. This is generally the way I handle inline-block:
Display:inline-block;
Zoom:1;
*display:inline;
thank you for example