我正在尝试使用具有不同指定高度的div 的flex-direction: column
创建布局。如果您为共享相同弹性框父项的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>
在我能够很好地了解如何有效地使用弹性框之前,我可能会回到在没有弹性框的情况下创建布局。我真的很想尽快开始使用它,尽管我遇到了这个问题,但它感觉不那么黑客了。
弹性格式上下文的范围是父子关系。
换句话说,弹性布局仅存在于弹性容器及其子容器之间。
子项以外的后代不参与弹性布局。
您要定位的元素是弹性项 (.site-title
的子元素,因此弹性属性不适用。
您必须将弹性项放入弹性容器中,以使弹性属性在 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>