垂直居中侧导航栏

时间:2016-11-25 21:03:21

标签: html css navbar

人。 我对CSS很陌生,这是我第一次尝试创建垂直导航栏。 在得知我需要为我的<li>使用-40 margin以使文本水平居中之后,我得到了下一个挑战。 我不认为它将文本垂直居中。 也许有人可以帮助我: - )

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>

4 个答案:

答案 0 :(得分:0)

少数事情:

.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增加了一个余量来平衡你的填充。

如果所有父母(html,body等)都没有定义适当的高度,

.nav {height:100%;}将无效。

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

*{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>

我做的是:

  • 添加了包裹ul
  • 的div
  • 增加高度:100%;到html,body和那个div
  • 添加了显示:table;那个div
  • 添加显示:table-cell;垂直对齐:中部;到你的.nav

答案 1 :(得分:0)

这样的东西?

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>

答案 2 :(得分:0)

一块蛋糕!只需应用以下规则:

.nav {
    padding: 0;
}

并且不要使用任何负边距。希望能帮到你: - )

答案 3 :(得分:0)

您可以使用flexbox 你添加到代码.nav

中调用的父ul
 display: flex;
justify-content: center;
align-items: center;
flex-direction: column;

和子元素(li)

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

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

justify-content: center;