注意:关于如何通过绝对定位,固定行高,桌面显示等在div环境中垂直居中内容已经有几个问题。
这个问题有所不同,因为它1.)强调一种灵活的方式来垂直居中上下文,而不是使用固定值2.)由于某些原因,当这些解决方案与节环境一起使用时,结果不符合预期。
那么如何在下面的代码中垂直居中导航栏呢?
.header {
width: 100%;
height: 115px;
margin: 0;
padding: 0;
background-color: lightgray;
text-align:center;
}
.header ul {
list-style-type: none;
}
.header li {
display: inline;
}
body {
margin: 0;
padding: 0;
}

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<section class="header">
<nav>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</nav>
</section>
</body>
</html>
&#13;
答案 0 :(得分:1)
Flexbox让这一切变得简单。只需将以下内容添加到.header
类:
.header {
width: 100%;
height: 115px;
margin: 0;
padding: 0;
background-color: lightgray;
text-align:center;
display: flex;
align-items: center;
justify-content: center;
}
.header ul {
list-style-type: none;
}
.header li {
display: inline;
}
body {
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<section class="header">
<nav>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</nav>
</section>
</body>
</html>
答案 1 :(得分:1)
一个简单的解决方案是使用transform: translate
Stack snippet
.header {
width: 100%;
height: 115px;
margin: 0;
padding: 0;
background-color: lightgray;
text-align:center;
}
.header nav { /* added rule to vertical align nav */
position: relative;
top: 50%;
transform: translateY(-50%);
}
.header img, .header ul { /* added rule for img and ul */
display: inline-block;
vertical-align: middle;
}
.header ul {
list-style-type: none;
}
.header li {
display: inline;
}
body {
margin: 0;
padding: 0;
}
&#13;
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<section class="header">
<nav>
<img src="http://placehold.it/40/f00" alt="">
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</nav>
</section>
</body>
</html>
&#13;
答案 2 :(得分:0)
Flexbox提供了最简单的答案:
.header {
width: 100%;
height: 115px;
margin: 0;
padding: 0;
background-color: lightgray;
text-align:center;
display: flex;
flex-direction: column;
justify-content: center;
}