Getting flex-box column to fill available space

Viewed 3951

I've been trying to get css flex box to work correctly for filling out items in column flex box.

Basically I want this code to evenly space the two flex pieces to each take up 50% of the available height. If I manually set the height to 50% it works, but that seems like the incorrect solution, as I thought that is what setting flex:1 was supposed to do.

I read the guide here: https://css-tricks.com/snippets/css/a-guide-to-flexbox/ and tried the various align-self, flex-grow, align-content to see if those would fix it, but so far I've had no luck. I'm sure I'm missing something simple, but I've just haven't been able to figure it out, and reading the other questions on stack overflow didn't seem to help me in figuring out what I'm doing incorrectly.

.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>

Full code here: https://codepen.io/anon/pen/EwbLMM

1 Answers

Make the container a flexbox too. Add display: flex to col-flex - see demo below:

.flex{
  display:flex;
}

.flex1{
  flex:1;
}

.col-flex{
  display: flex; /* ADDED */
  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>
  

Related