无法在不影响导航栏大小的情况下更改导航栏内的 <li> 垂直位置

Cant change <li> vertical position inside nav bar without affecting nav bar's size

所以我尝试更改 li 的垂直位置,但是当我这样做时,导航栏的高度也会受到影响。在不影响导航栏高度的情况下实际执行此操作的方法是什么?

代码如下:

body {
  margin: 0px;
}

ul {
  margin: 0px;
  padding: 0px;
  list-style: none;
  padding-left: 5px;
  padding-top: 10px;
  background-color: #333;
  overflow: hidden;
}

li {
  float: left;
  height: 30px;
  width: 100px;
  background-color: grey;
  color: white;
  margin-right: 4px;
  text-align: center;
  line-height: 30px;
  font-weight: bold;
  font-size: 15px;
}

li a {
  text-decoration: none;
  color: white;
  display: block;
}

ul li:hover {
  opacity: 0.8;
}
<ul>
  <li><a href="kalli.html">Home</a></li>
  <li><a href="mp.html">My Profile</a></li>
  <li><a href="set.html">Settings</a></li>
</ul>

你的目标是什么?使内容居中还是...?

在这里使用 flexbox 可能比在你的 ul 上设置 padding-left: 850px; 更好(在你的 ul 上你也可以使用 display: block; margin: 0 auto; 来居中。)如果如果你愿意,你可以给你的 ul 一个定义的高度并使用 align-items 来指定它应该如何垂直对齐。

body {
  margin: 0;
}


nav {
  background-color: #333;
  display: flex;
  justify-content: center;
}

nav ul {
  display: flex;
  justify-content: center;
  list-style: none;
  margin: 0;
  padding: 0;
  height: 50px;
  align-items: center;
}

li {
  height: 30px;
  width: 100px;
  background-color: grey;
  color: white;
  margin-right: 4px;
  text-align: center;
  line-height: 30px;
  font-weight: bold;
  font-size: 15px;
}
li a {
  text-decoration: none;
  color: white;
  display: block;
}
ul li:hover {
  opacity: 0.8;
}
<body>
  <nav>
    <ul>
      <li><a href="kalli.html">Home</a></li>
      <li><a href="mp.html">My Profile</a></li>
      <li><a href="set.html">Settings</a></li>
    </ul>
  </nav>
</body>

您可以在我的代码段 bottom: 4px;:

中添加 position: relative;bottomtop- 的值

这里保留了元素原本占用的space(没有position: relative;),而是按照top/bottom/left/right设置移动元素,不影响其他元素

body {
  margin: 0px;
}

ul {
  margin: 0px;
  padding: 0px;
  list-style: none;
  padding-left: 5px;
  padding-top: 10px;
  background-color: #333;
  overflow: hidden;
}

li {
  float: left;
  height: 30px;
  width: 100px;
  background-color: grey;
  color: white;
  margin-right: 4px;
  text-align: center;
  line-height: 30px;
  font-weight: bold;
  font-size: 15px;
  position: relative;
  bottom: 4px;
}

li a {
  text-decoration: none;
  color: white;
  display: block;
}

ul li:hover {
  opacity: 0.8;
}
<ul>
  <li><a href="kalli.html">Home</a></li>
  <li><a href="mp.html">My Profile</a></li>
  <li><a href="set.html">Settings</a></li>
</ul>