2017-10-14 31 views
1

我想讓我的導航欄中的按鈕顯示在導航欄的中心,但我似乎只能讓它們出現在左側或右側。我如何居中它們?這裏是我的CSS代碼:如何將我的導航欄中的元素居中?

body{ 
background-color:#d9dbdd; 
} 

#nav { 
list-style-type: none; 
margin: 0; 
padding: 0; 
overflow: hidden; 
background-color: #333; 
top: 0; 
width: 100%; 
z-index: 999999; 
position:fixed; 
} 

#nav li { 
float: left; 
} 

#nav li a { 
display: block; 
color: white; 
text-align: center; 
padding: 14px 16px; 
text-decoration: none; 
} 

#nav li a:hover:not(.active) { 
background-color: #111; 
} 

.active { 
background-color: #007ed8; 
} 

的jsfiddle:加入https://jsfiddle.net/ctjhvz6u/

回答

2

取消已宣佈float: left規則你#nav li,而是添加display: inline-block,然後在#nav上聲明text-align: center

在有問題的元素上聲明float規則時,您將無法對齊任何中心。如果您在包含的父元素上聲明text-align: center,則任何您設計爲display: inline-block的元素都可以水平對齊。

body { 
 
    background-color: #d9dbdd; 
 
} 
 

 
#nav { 
 
    list-style-type: none; 
 
    margin: 0; 
 
    padding: 0; 
 
    overflow: hidden; 
 
    background-color: #333; 
 
    top: 0; 
 
    width: 100%; 
 
    z-index: 999999; 
 
    position: fixed; 
 
    text-align: center; 
 
} 
 

 
#nav li { 
 
    display: inline-block; 
 
} 
 

 
#nav li a { 
 
    display: block; 
 
    color: white; 
 
    text-align: center; 
 
    padding: 14px 16px; 
 
    text-decoration: none; 
 
} 
 

 
#nav li a:hover:not(.active) { 
 
    background-color: #111; 
 
} 
 

 
.active { 
 
    background-color: #007ed8; 
 
}
<ul id="nav" class="bg-inverse navbar-inverse"> 
 
    <li><a class="active" href="#despre">Despre mine</a></li> 
 
    <li><a href="#educatie">Educatie</a></li> 
 
    <li><a href="#aptitudini">Aptitudini</a></li> 
 
    <li><a href="#experienta">Experienta</a></li> 
 
    <li><a href="#contact">Contact</a></li> 
 
</ul>

小提琴:https://jsfiddle.net/ctjhvz6u/1/

1

您可以用Flexbox的做到這一點:

#nav { 
    display: flex; /* displays children inline */ 
    justify-content: center; /* horizontal alignment/centering */ 
} 
2

刪除此:

#nav li { 
    float: left; 
} 

,並加入到#nav

display: flex; 
align-items:center; 
justify-content: center; 

我建議你使用

display: -webkit-box; 
display: -moz-box; 
display: -ms-flexbox; 
display: -webkit-flex; 
display: flex; 

爲了確保代碼的最瀏覽器上運行。