如何在动态高度的flexbox中进行div拉伸?

时间:2017-01-05 04:51:59

标签: css flexbox

我正在尝试使用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是父容器的大小 - 换句话说,顶部应伸展以填充容器。

当我有容器高度时,我知道如何执行此操作,但我宁愿避免在运行时确定该变量。

此问题已经以各种形式详细介绍,但似乎没有解决这个简单的用例(here,例如,使用标题/内容/页脚,但表面上不仅仅是内容/页脚)。

我已经设置了codepen with the example

3 个答案:

答案 0 :(得分:3)

我认为这是使用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>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

最小代码行。 布拉德的答案是正确的。但在这里,我使用了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 此处

答案 2 :(得分:1)

只需使用CSS Calc

就可以在没有flexbox的情况下完成

&#13;
&#13;
html, body {
  margin: 0;
}
.container {
  height: 100vh;
}
.top {
  background: lightblue;
  height: calc(100% - 100px);
}
.bottom {
  height: 100px;
  background: lightgreen;
}
&#13;
<div class="container">
  <div class="top"></div>
  <div class="bottom"></div>
</div>
&#13;
&#13;
&#13;

如果您希望它在旧版浏览器上运行,请更新这些规则

html, body {
  margin: 0;
  height: 100%;
}
.container {
  height: 100%;
}