我正在学习使用flexbox,但无法在类.headercontent
内垂直对齐内容。它似乎尊重justify-content
之类的所有其他事物,但忽略了align-content
。我搜索并发现了this线程,这似乎表明应明确设置父级的高度。我通过设置flex-basis
和flex-grow
以及min-height
来设置高度。但是仍然由div
包含h1
停留在header
的顶部。我希望该绿色div位于header
的垂直中心。我在做什么错了?
html {
box-sizing: border-box;
margin: 0;
padding: 0;
font-size: 100%;
line-height: 1.2em;
}
body {
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: stretch;
height: 100vh;
background-color: #cdc9c1;
}
header {
background-color: #a99879;
flex-basis: 10%;
flex-grow: 1;
min-height: 20px;
}
main {
background-color: #5b431a;
flex-basis: 80%;
flex-grow: 8;
}
footer {
background-color: #77613c;
flex-basis: 10%;
flex-grow: 1;
}
.headercontent {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
background-color: green;
min-height: 20px;
}
.navstyle {
list-style-type: none;
}
<html>
<head>
</head>
<body>
<header>
<div class="headercontent">
<h1>This is the header</h1>
</div>
</header>
<nav>
<ul>
<li>section1</li>
<li>section2</li>
<li>section3</li>
</ul>
</nav>
<main>
<p> this is the main body</p>
</main>
<footer>
<p> this is the footer </p>
</footer>
</body>
</html>
这是我的作品https://codepen.io/knows_not_much/pen/rNxXoOM的可待因链接
答案 0 :(得分:1)
我希望绿色div位于标题的垂直中心。什么 我做错了吗?
您的header
元素占据body
高度的10%。您的.headercontent
不会占据header
的整个定义高度。因此,它将位于顶部。为了解决这个问题,您可以将header
元素分配为flex容器,也就是在其中分配align-items: center; justify-content: center
属性的地方
header {
background-color: #a99879;
flex-basis: 10%;
flex-grow: 1;
display: flex; /* add these */
align-items: center; /* add these */
justify-content: center; /* add these */
}
如果必须让绿色背景占用空间,请随后根据需要将width: 100%
分配给.headercontent