html - 如何使导航栏中的元素居中?

标签 html css bootstrap-4

我希望导航栏中的按钮出现在导航栏的中央,但我似乎只能让它们出现在左侧或右侧。我如何将它们居中?这是我的 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/

相关文章:

隐藏 div 的 jQuery 计数器

html - 缩小图像并保持纵横比

html - 悬停时菜单项移动

css - 如何在单击时隐藏可折叠的 Bootstrap 导航栏

javascript - 如何对齐div边框内的文本标题

grails - 在 grails 3 应用程序中,什么是微调器,我需要 application.js 吗?

html - LI visibility 与 UL 高度无关

javascript - CSS3 - 如何交叉淡化未知高度的图像并将它们垂直和水平居中

CSS ie6 悬停问题

javascript - 无法访问 html5 Canvas ?