2013-10-02 81 views
-1

文本应该位于导航栏的中间(垂直)。垂直对齐:中间不工作

我的代码无法正常工作。

任何人都可以解释,为什么?

<style> 
#navigationbar { 
background: rgb(252,219,121); 
background: -moz-linear-gradient(top, rgba(252,219,121,1) 2%, rgba(254,191,1,1) 100%); 
background: -webkit-gradient(linear, left top, left bottom, color-stop(2%,rgba(252,219,121,1)), color-stop(100%,rgba(254,191,1,1))); /* Chrome,Safari4+ */ 
background: -webkit-linear-gradient(top, rgba(252,219,121,1) 2%,rgba(254,191,1,1) 100%); 
background: -o-linear-gradient(top, rgba(252,219,121,1) 2%,rgba(254,191,1,1) 100%); 
background: -ms-linear-gradient(top, rgba(252,219,121,1) 2%,rgba(254,191,1,1) 100%); 
background: linear-gradient(to bottom, rgba(252,219,121,1) 2%,rgba(254,191,1,1) 100%); 
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fcdb79', endColorstr='#febf01',GradientType=0); 
height: 40px; 
} 

#logo { 
color:white; 
vertical-align:middle; 
margin-left:10px; 
} 

* { 
margin:0px; 
} 
</style> 
<link rel="stylesheet" type="text/css" href="style.css"> 

<div id='navigationbar'> 
    <a id='logo' href='http://localhost/'>WORK.</a> 
</div> 

回答

1

您需要在容器上设置垂直对齐的行高来知道垂直中间的东西。见JSBIN demo

#navigationbar { 
background: rgb(252,219,121); 
background: -moz-linear-gradient(top, rgba(252,219,121,1) 2%, rgba(254,191,1,1) 100%); 
background: -webkit-gradient(linear, left top, left bottom, color-stop(2%,rgba(252,219,121,1)), color-stop(100%,rgba(254,191,1,1))); /* Chrome,Safari4+ */ 
background: -webkit-linear-gradient(top, rgba(252,219,121,1) 2%,rgba(254,191,1,1) 100%); 
background: -o-linear-gradient(top, rgba(252,219,121,1) 2%,rgba(254,191,1,1) 100%); 
background: -ms-linear-gradient(top, rgba(252,219,121,1) 2%,rgba(254,191,1,1) 100%); 
background: linear-gradient(to bottom, rgba(252,219,121,1) 2%,rgba(254,191,1,1) 100%); 
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fcdb79', endColorstr='#febf01',GradientType=0); 
height: 40px; 
    line-height:40px; 
} 
2

vertical-align仅适用于具有特定属性的元素,一般用CSS表display属性(table-celltabletable-row等等)。

但是,当您知道容器的高度时,有一种简单的方法可将事物垂直居中。只需将line-height: 40px添加到您的#logo CSS(您可以将其添加到容器中,但在这种情况下没有任何区别)。

#logo { 
    color:white; 
    line-height: 40px; 
    margin-left:10px; 
} 

如果你想使用vertical-align,你就需要设置display: table容器(#navigationbar)和display: table-cell#logovertical-align: middle上。这将达到相同的效果。

+1

很好的解释! :) – gnclmorais

1

添加到您当前的CSS(demo here):

#navigationbar { 
    width: 100%; 
    display: table; 
} 

#logo { 
    display: table-cell; 
} 

如@Ennui说:

vertical-align仅适用于具有特定属性的元素,一般用CSS表显示属性(table-celltable,table-row等)。

1

您可以使用line-height:33px; ,但我还建议将'标签'包装到'div标签'中,以便以后操作时很容易。例如:

<style> 
#logo { 
width: 30px; 
height: 40px; 
    margin-left: 10px; 
} 
#logo a{ 
color: white; 
line-height: 33px; 
} 
</style> 
<body> 
<div id='navigationbar'> 
    <div id='logo'><a href='http://localhost/'>WORK.</a></div> 
</div> 
</body> 

如果您需要稍后移动该徽标,则可以轻松在#logo上使用绝对值。