我正在尝试使用flexbox制作一个堆叠布局。理想情况下,它应该是这样的:
其中底部(蓝色)div的高度固定为250px
,而顶部div的高度为n-250
,其中n
是父容器的大小--换句话说,顶部应该扩展以填充整个容器。当我有容器高度时,我对如何实现此功能有一些想法,但我宁愿避免在运行时确定该变量。
这个问题已经在各种形式下详细讨论过了,但似乎没有一个解决这个简单用例的(例如,这里,适用于标题/内容/页脚,但显然不适用于只有内容/页脚)。
我已经设置了一个带有示例的CodePen。
我正在尝试使用flexbox制作一个堆叠布局。理想情况下,它应该是这样的:
其中底部(蓝色)div的高度固定为250px
,而顶部div的高度为n-250
,其中n
是父容器的大小--换句话说,顶部应该扩展以填充整个容器。我认为使用 flex-grow: 1;
来回答你的问题。希望对你有所帮助。
https://jsfiddle.net/BradChelly/ck72re3a/
.container {
width: 100px;
height: 150px;
background: #444;
display: flex;
flex-direction: column;
align-content: stretch;
}
.box1 {
width: 100%;
background: steelblue;
flex-grow: 1;
}
.box2 {
height: 50px;
width: 100%;
background: indianred;
}
<div class="container">
<div class="box1"></div>
<div class="box2"></div>
</div>
最少的代码行数。Brad的答案是正确的。但是这里我使用了flex
代替flex-grow
并且删除了align-items
.container {
width: 100px;
height: 100vh;
display: flex;
flex-direction: column;
}
.top {
width: 100%;
background: blue;
flex: 1;
}
.bottom {
height: 70px;
width: 100%;
background: green;
}
<div class="container">
<div class="top"></div>
<div class="bottom"></div>
</div>
Demo here
flex
而不是 flex-grow
的原因是什么? - user663031可以通过简单地使用CSS Calc而无需使用flexbox
来完成。
html, body {
margin: 0;
}
.container {
height: 100vh;
}
.top {
background: lightblue;
height: calc(100% - 100px);
}
.bottom {
height: 100px;
background: lightgreen;
}
<div class="container">
<div class="top"></div>
<div class="bottom"></div>
</div>
html, body {
margin: 0;
height: 100%;
}
.container {
height: 100%;
}
flex-grow
更复杂? - user663031