我希望导航栏中的按钮出现在导航栏的中央,但我似乎只能让它们出现在左侧或右侧。我如何将它们居中?这是我的 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/
最佳答案
删除您在#nav li
上声明的float: left
规则,而是添加display: inline-block
,然后声明text-align: center
在 #nav
上。
在相关元素上声明了 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>
fiddle : https://jsfiddle.net/ctjhvz6u/1/
关于html - 如何使导航栏中的元素居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46746703/