Search code examples
htmlvertical-alignmentcss

Vertical Align Inline-Block With Height 100%


First I'll list my code and the link to JSFiddle.

HTML

<div id="wrapper">
    <div id="container">
        <div id="content">
            Here is the content
        </div>
    </div>
</div>

JS

body,html{height:100%;}
#wrapper{
    height:100%;
    background-color:green;
}
#container {
    display: inline-block ;
    height:100%;
    width:100%;
    background-color:red;
    text-align:center;
    vertical-align:middle;
}
#content
{
    display:inline-block;
    background-color:blue;
}

http://jsfiddle.net/x11joex11/b4ZBg/

(Newer one with more content for vertical center testing)

http://jsfiddle.net/x11joex11/sDWxN/11/

What I'm trying to do is vertically center the blue highlighted DIV in the center of the red div. Is there a way to do this using inline-block and not table-cells?

The height of the containing div also HAS to be 100% not a set pixel amount.

The content will also be variable height

I am trying to avoid table-cell display because of browser bugs, but if it's the only option I would like to know that also. Any solution to this issue would be appreciative.


Solution

  • The art of vertical centring with inline-block is to understand that the inline-level elements are centred in their line-box. So you need to make the line-height match the height of the containing box.

    The line-height is determined by a combination of the line-height setting of the containing block and the content of the line.

    However the line-height of the containing box cannot be set in terms of a percentage of the height of the containing box, so that provides no solution.

    Instead, we can create some content on the same line as the content we want to align that's the height of the containing block using

    #container:before {
        display:inline-block;
        content: '';
        height:100%;
        vertical-align:middle;
    }
    

    which will force the line height be tall enough to contain that content.

    The other thing necessary is to note that vertical-align is applied to the boxes being aligned, rather than the containing box.

    The result is http://jsfiddle.net/9j95x/