垂直居中侧导航栏

vertical centering Side Navbar

伙计们。 我是 CSS 的新手,这是我第一次尝试创建垂直导航栏。 在了解到我需要为我的 <li> 使用 -40 边距以使文本水平居中后,我遇到了下一个挑战。 我不明白它使文本垂直居中。 也许有人可以帮助我:-)

body {
  font-family: Lato;
}

.nav {
  width: 300px;
  height: 100%;
  margin: -8px;
  background-color: grey;
}

.nav li {
  list-style: none;
  text-align: center;
  margin: 0 0 0 -40;
}

.nav li a {
  text-decoration: none;
  color: black;
  font-weight: bold;
  
}

.nav li a:hover {
  color: white;
}
<html>

<head>
  <meta charset="utf-8">
  <link href="style.css" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
  <title>Webdesign</title>
</head>
  
<body>
  <ul class="nav">
  <li><a href="#">START</a></li>
  <li><a href="#">HOME</a></li>
  <li><a href="#">CONTACT</a></li>
  </ul>
</body>


</html>

几件事:

.nav li {
list-style: none;
text-align: center;
margin: 0 0 0 -40; // You forgot to define a unit, so it won't work. (40 what ? px, em, rem, %...)
}

我建议您重置边距和填充 * {margin:0; padding:0;},因为您在 li 中添加了边距以平衡 th ul 的填充。

.nav {height:100%;} 如果所有 parents(html、body 等)都没有定义合适的高度,那么

将无法工作。

您可以通过不同的方式实现垂直对齐, 一个是:

*{padding:0; margin:0;}
html, body {height:100%;}
body {
  font-family: Lato;
    vertical-align:middle;
}
div {
  display:table;
  height:100%;
}
.nav {
  width: 300px;
  height: 100%;
  background-color: grey;
  display:table-cell;
  vertical-align:middle;
}

.nav li {
  list-style: none;
  text-align: center;
}

.nav li a {
  text-decoration: none;
  color: black;
  font-weight: bold;
  
}

.nav li a:hover {
  color: white;
}
<body>
  <div>
    <ul class="nav">
      <li><a href="#">START</a></li>
      <li><a href="#">HOME</a></li>
      <li><a href="#">CONTACT</a></li>
    </ul>
  </div>
</body>

我做的是:

  • 添加了一个 div 包装 ul
  • 添加了height:100%;到 html、正文和那个 div
  • 已添加display:table;那个 div
  • 已添加 display:table-单元格; vertical-align:中间;到你的 .nav

是这样的吗?

body {
  font-family: Lato;
}

.nav {
  width: 300px;
  height: 100%;
  margin: 0px;
  padding: 0px;
  background-color: grey;
  text-align: center;
}

.nav li {
  display: block;
  list-style: none;
}

.nav li a {
  text-decoration: none;
  text-align: center;
  color: black;
  font-weight: bold;
  display: block;
}

.nav li a:hover {
  color: white;
}
<html>

<head>
  <meta charset="utf-8">
  <link href="style.css" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
  <title>Webdesign</title>
</head>
  
<body>
  <ul class="nav">
  <li><a href="#">START</a></li>
  <li><a href="#">HOME</a></li>
  <li><a href="#">CONTACT</a></li>
  </ul>
</body>


</html>

小菜一碟!只需应用以下规则:

.nav {
    padding: 0;
}

并且不要使用任何负边距。希望对你有帮助:-)

你可以使用flexbox 您添加到代码中调用的父 ul .nav

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

和子元素 (li)

flex-wrap: wrap-reverse;
align-self: center;

Flexbox 可以确保您的项目将 100% 在中间垂直使用:

justify-content: center;