如何在动态高度的flexbox中使一个div拉伸?

7

我正在尝试使用flexbox制作一个堆叠布局。理想情况下,它应该是这样的:

2 boxes stacked vertically, the top is red and 4x the size of the bottom, which is blue

其中底部(蓝色)div的高度固定为250px,而顶部div的高度为n-250,其中n是父容器的大小--换句话说,顶部应该扩展以填充整个容器。
当我有容器高度时,我对如何实现此功能有一些想法,但我宁愿避免在运行时确定该变量。
这个问题已经在各种形式下详细讨论过了,但似乎没有一个解决这个简单用例的(例如,这里,适用于标题/内容/页脚,但显然不适用于只有内容/页脚)。
我已经设置了一个带有示例的CodePen

1
为什么这比在顶部div上使用flex-grow更复杂? - user663031
1
在你的 CodePen 中,有两个 HTML 错误阻止了它的工作。一个是 </top> 而不是 </div>,另一个是 bottom="bottom" 而不是 id="bottom"。 - Brad
1
http://codepen.io/anon/pen/ygygmy - Brad
1
如果容器的高度未知或无法解决(例如,固定值),那么通常情况下,您无法。请注意,下面所有当前的答案都需要知道容器的高度。如果不知道...它们将不起作用AFAIK。 - Paulie_D
3个回答

12

我认为使用 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>


我知道...仍然很糟糕,甚至Crayola也放弃了“肉色”和“印度红”。 - keeg

3

最少的代码行数。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
简写,例如使用 border 代替 border-color。 - Brad

1

可以通过简单地使用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%;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接