获取flex-box列以填充可用空间

时间:2017-10-04 16:06:31

标签: html css css3 flexbox alignment

我一直试图让css flex box正常工作,以填充列弹性框中的项目。

基本上我希望这段代码能够均匀地将两个弹性片空间分开,每个弹片占据可用高度的50%。如果我手动将高度设置为50%它可以工作,但这似乎是不正确的解决方案,因为我认为这是设置flex:1应该做的。

我在这里阅读了指南:https://css-tricks.com/snippets/css/a-guide-to-flexbox/并尝试了各种align-self,flex-grow,align-content以查看是否会修复它,但到目前为止我还没有运气。我确定我错过了一些简单的东西,但我还没有能够弄清楚,并且在堆栈溢出上阅读其他问题似乎没有帮助我弄清楚我做错了什么。



.flex {
  display: flex;
}

.flex1 {
  flex: 1;
}

.col-flex {
  flex-flow: column nowrap;
  justify-content: space-evenly;
}

<div class="flex" style="height:200px">
  <div class="flex1">
    <div class="col-flex" style="height:100%;background-color:grey">
      <div class="flex1" style="background-color:blue;flex-grow:1">I should be top half, you shouldn't see grey</div>
      <div class="flex1" style="background-color:green;flex-grow:1">I should be bottom half, you shouldn't see grey</div>
    </div>
  </div>
  <div class="flex1" style="background-color: red;">
    The flex on the row based flex works correctly;
  </div>
</div>
&#13;
&#13;
&#13;

此处的完整代码:https://codepen.io/anon/pen/EwbLMM

1 个答案:

答案 0 :(得分:2)

使容器成为 flexbox 。将display: flex添加到col-flex - 请参阅下面的演示:

&#13;
&#13;
.flex{
  display:flex;
}

.flex1{
  flex:1;
}

.col-flex{
  display: flex; /* ADDED */
  flex-flow: column nowrap;
  justify-content: space-evenly;
}
&#13;
<div class="flex" style="height:200px">
  <div class="flex1">
    <div class="col-flex" style="height:100%;background-color:grey"> 
      <div class="flex1" style="background-color:blue;flex-grow:1">I should be top half, you shouldn't see grey</div>
      <div class="flex1" style="background-color:green;flex-grow:1">I should be bottom half, you shouldn't see grey</div>
    </div>
  </div>
  <div class="flex1" style="background-color: red;">
    The flex on the row based flex works correctly;
  </div>
</div>
  
&#13;
&#13;
&#13;