2

我有以下菜单结构:

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

#main-nav在这种情况下,容器是真实的height: 20px;.menu-main-menu-container也是如此)。但是当我尝试.header使用这个垂直定位整个菜单时:

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

瞬间#main-nav得到高度.header!所以,它是height: 150px;(根据 Firebug),我不能垂直定位它。

我如何垂直定位它?这是我经常偶然发现的错误。当我添加 top: 0; 和底部:0;它获取父容器的高度。我不知道那个菜单的高度。

4

2 回答 2

4

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

于 2012-05-28T13:00:07.593 回答
-1

I'm thinking that you mean center horizontally. In which case you cannot do that if your height is unknown by CSS only. You can use jQuery for that though. Take a look at this fiddle.

It calculates the height of your menu and then calculates where it has to be positioned.

于 2012-05-28T12:57:49.353 回答