cssheightflexboxstretch

Flexbox: How to Combine percent, pixels and remaining height on columns?


I'm building basic grid system and need to combine height of flex-items described in different size units, which are %, px and remaining space.

html:

<div class="grid">
  <div class="block" style="flex-basis: 50px;">50px</div>
  <div class="block" style="flex-basis: 25%;">25%</div>
  <div class="block">stretch to remaining space?</div>
  <div class="block" style="flex-basis: 50px;">50px</div>
</div>

css:

html,body,.grid {
  height: 100%;
  padding: 0;
  margin: 0;
}
.grid {
  width: 300px;
  background: #aaa;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;

}
.block {
  outline: solid 1px black;
  flex-grow: 0; // remove growing proportion
  flex-shrink: 0; // remove shrinking proportion
}

working example: http://codepen.io/antraxis/pen/zxwgEo


Solution

  • Use the flex-grow parameter (the first one in the flex shorthand property) :

    * { margin: 0; box-sizing: border-box; }
    
    .grid {
      height: 100dvh;
      background: #aaa;
      display: flex;
      flex-direction: column;
    }
    
    .block {
      outline: solid 1px black;
    }
    
    .a {
      flex: 0 0 50px;
    }
    
    .b {
      flex: 0 0 15%;
    }
    
    .c {
      flex: 1 0 0;
    }
    <div class="grid">
      <div class="block a">block height 50px</div>
      <div class="block b">block height 15%</div>
      <div class="block c">block height *</div>
      <div class="block a">block height 50px</div>
    </div>

    codepen