我正在尝试使用 flex-direction: column
和具有不同指定高度的 div 创建布局。如果您为共享同一个 flexbox parent 的 div 指定不同的高度,我发现垂直对齐消失了。
我尝试了各种使用 align-items
、align-content
、justify-content
的组合,但都无济于事。我用 flex-grow
代替了同样没有效果的高度规则。使内容垂直居中的唯一方法是使所有元素的相对高度相同。
header {
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
text-align: center;
height: 40em;
background-color: #badabf;
}
.site-title {
height: 32em;
background-color: #DEA5A4;
}
.site-navigation {
height: 8em;
background-color: #AEC6CF;
}
<header>
<div class="site-title">
<h1> I am a page title </h1>
<img src="http://www.nintendo.com/images/social/fb-400x400.jpg" width="100" height="100">
</div>
<nav class="site-navigation">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">History</a></li>
<li><a href="#">Events</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</header>
在我能够很好地理解如何有效地使用 flexbox 之前,我可能会回到创建没有 flexbox 的布局。我真的很想尽快开始使用它,尽管我遇到了这个问题,但感觉不那么笨拙了。
最佳答案
flex 格式化上下文的范围是父子关系。
换句话说, flex 布局只存在于 flex 容器和它的子容器之间。
child 以外的后代不参与 flex 布局。
您定位的元素是 flex 元素 (.site-title
) 的子元素,因此 flex 属性不适用。
您必须将 flex 元素制作成 flex 容器,以使 flex 属性在 HTML 结构中更深入地工作。
header {
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
text-align: center;
height: 40em;
background-color: #badabf;
}
.site-title {
height: 32em;
background-color: #DEA5A4;
display: flex; /* NEW */
flex-direction: column; /* NEW */
align-items: center; /* NEW */
justify-content: center; /* NEW */
}
.site-navigation {
height: 8em;
background-color: #AEC6CF;
}
<header>
<div class="site-title">
<h1> I am a page title </h1>
<img src="http://www.nintendo.com/images/social/fb-400x400.jpg" width="100" height="100">
</div>
<nav class="site-navigation">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">History</a></li>
<li><a href="#">Events</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</header>
关于html - 使用 flex-direction : column 将不同高度的内容垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42749968/