Search code examples
htmlcssvertical-alignment

CSS vertical positioning, no height known


I've got the following menu structure:

<div class="header" style="height: 150px;">
    <nav id="main-nav">
        <div class="menu-main-menu-container">
            <ul id="menu">
                <li>menu item 1</li>
                <li>menu item 2</li>
            </ul>
        </div>
        <div class="clear"></div>
    </nav>
</div>

Container #main-nav in this case has real height: 20px; (so .menu-main-menu-container has it, too). But when I try to vertically position entire menu in .header using this:

#main-nav {
    bottom: 0;
    margin: auto;
    position: absolute;
    right: 0;
    top: 0;
}

The #main-nav instantly gets height of the .header! So, it's height: 150px; (according to Firebug) and I can't vertically position it.

How do I vertically position that? That's the bug I stumble upon quite often. When I add top: 0; and bottom: 0; it gets height of parent container. I don't know height of that menu.


Solution

  • Situation when height of the parent is unknown and the height of the child known: Set top: 50% and margin-top: -10px (10px = half the height of the nav). Demo http://dabblet.com/gist/2819055

    Situation when both the heights of the parent and the child are unknown: Use a pseudo-element of height: 100%; display: inline & vertical-align: middle on both the pseudo-element and the child (nav in this case) - demo http://dabblet.com/gist/2819071