oo2bqg
Last Updated: February 25, 2016
·
8.726K
· idered

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

17 Responses
Add your response

481

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

over 1 year ago ·
485

nice once :D

over 1 year ago ·
544

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

over 1 year ago ·
546

@emilnordh What about IE8?

over 1 year ago ·
547

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

over 1 year ago ·
551

@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 ;)

over 1 year ago ·
561

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

over 1 year ago ·
564

@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?

over 1 year ago ·
565

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

over 1 year ago ·
3192

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!

over 1 year ago ·
3236

@emilnordh IE7 = .87% users. Screw them. :)

Btw great tip. Thanks so much.

over 1 year ago ·
3441

@nathansmonk IE8 don't work

over 1 year ago ·
3442

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

over 1 year ago ·
3443
over 1 year ago ·
3446

With IE7 you may have to force haslayout. This is generally the way I handle inline-block:

Display:inline-block;
Zoom:1;
*display:inline;

over 1 year ago ·
3467

I can't seem to implement it. It doesn't work.

over 1 year ago ·
3700

thank you for example

over 1 year ago ·