我难以在其父div中垂直对齐nav元素。

时间:2014-06-21 15:25:38

标签: html css alignment vertical-alignment

我尝试的一切都会产生一个新问题。当我使用line-height:属性时,它经常会被推出。我怎样才能成功地将这个元素集中在一起?

CSS:

#parent {
    background: #000; 
    background: rgba(0,0,0,0.50);
    width: 100%;
    height: 70px;
    position: fixed ;
    z-index: 9999;
}

#child {
    display: inline;
    text-align: center;
    float: right;
    margin-right: 30px; 
}

ul.menu2 {
    cursor: default;
    border-bottom: 0;
    margin-bottom: 0;
}

ul.menu2 li {
    display: inline-block;
    line-height: 1em;
    padding: 0 0 0 0.5em;
    margin: 0 0 0 0.5em;
}

HTML:

<div id="parent">
        <nav id="child" role="navigation">
            <ul class="menu2">
                <li><a href="#home" rel="home_link" class="scrolly">Home</a></li>
                <li><a href="#banner" rel="about_link" class="scrolly scrolly-centered">About</a></li>
                <li><a href="#first" rel="events_link" class="scrolly">Shows</a></li>
                <li><a href="#" rel="artists_link">Music</a></li>
                <li><a href="#" rel="contact_link">Contact</a></li>
            </ul>
        </nav>  
    </div>

3 个答案:

答案 0 :(得分:2)

如果您要line-heightinline-block使用vertical-align,则不应使用floattext-align会这样做。

您可以使用height设置nav line-height,并在其中间设置ul

<强> DEMO

#parent {
    background: #000; 
    background: rgba(0,0,0,0.50);
    width: 100%;
    top:0;
    left:0;
    text-align:right;/* ul will go right */
    line-height: 70px;/* as ul should stand on one line, it is enought to size height of nav */
    position: fixed ;
    z-index: 1;/* 1 should do it */
}

#child {
    display: inline-block;/* make me an inline-box, now i can hold anything, block, float, multi-lines, .. */
    text-align: center;/* reset text-align */
    margin-right: 30px; /* or padding-right, whatever */
    vertical-align:middle;/* set me on middle of line-height */
}

ul.menu2 {
    cursor: default;
    border : 0;
    margin : 0;/* usefull reset i believe :) */
    line-height:1.2em; /* reset line-height here to regular values :) in case text , inline-boxes split on 2 or more lines*/
}

ul.menu2 li {
    display: inline-block;
    padding: 0 0 0 0.5em;
    margin: 0 0 0 0.5em;
}

答案 1 :(得分:1)

<强> Demo

ul.menu2 {
    cursor: default;
    border-bottom: 0;
    margin-bottom: 0;
    margin-top: 0; /* add this to remove default margin from ul */
}
ul.menu2 li {
    display: inline-block;
    line-height: 70px; /* add this equal to the height of the parent to make it vertical center*/
    padding: 0 0 0 0.5em;
    margin: 0 0 0 0.5em;
}

答案 2 :(得分:1)

您可以使用表格布局:

#child {
   text-align: center;
   margin-right: 30px; 
   height: 100%;
}

ul.menu2 {
   cursor: default;
   margin: 0;
   height: 100%;
   display: table;
}

ul.menu2 li {
   display: table-cell;
   height: 100%;
   vertical-align: middle;
   line-height: 1em;
   padding: 0 0 0 0.5em;
   margin: 0 0 0 0.5em;
}

JSFiddle