Last Updated: September 29, 2020
·
9.349K
· 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

16 Responses
Add your response

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

over 1 year ago ·

nice once :D

over 1 year ago ·

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

over 1 year ago ·

@emilnordh What about IE8?

over 1 year ago ·

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 ·

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

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

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

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

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 ·

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

Btw great tip. Thanks so much.

over 1 year ago ·

@nathansmonk IE8 don't work

over 1 year ago ·

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 ·
over 1 year ago ·

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 ·

thank you for example

over 1 year ago ·