htmlcssflexboxresponsive-design

css flex-wrap, but vertically?


5 children elements

I would like to do EXACTLY what flex wrap row does, but VERTICALLY.

.container {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  gap: 5px;
  border: 2px solid #000;
  padding: 10px;
}

.box {
  width: 80px;
  height: 50px;
  background-color: orange;
}
<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

i would basically like to transpose the direction/axis of the wrap (so the wrap would go to the next column, when it reaches the vertical maximum of the parent container.)

all the vertical/column flexings don't create more than one column (wrap over to the next column)

image of what im talking about:

enter image description here

I have tried every combination/permutation of the flex styling params (for both the parent & children)

thanks!


Solution

  • To make a column flexbox wrap you need to limit the height, just like you limit the width when you want a row flexbox to wrap:

    :root {
      --box-width: 80px;
      --box-height: 50px;
      --gap: 5px;
      --col-items: 5;
    }
    
    .container {
      display: flex;
      flex-wrap: wrap;
      flex-direction: column;
      gap: var(--gap);
      width: 200px;
      height: calc(
        var(--col-items) * var(--box-height) + 
        (var(--col-items) - 1) * var(--gap)
      );
      border: 2px solid #000;
      padding: 10px;
    }
    
    .box {
      width: var(--box-width);
      height: var(--box-height);
      background-color: orange;
    }
    <div class="container">
      <div class="box">1</div>
      <div class="box">2</div>
      <div class="box">3</div>
      <div class="box">4</div>
      <div class="box">5</div>
      <div class="box">6</div>
      <div class="box">7</div>
      <div class="box">8</div>
    </div>

    Another option is to use CSS columns that will balance the number of items in each column:

    :root {
      --box-width: 80px;
      --box-height: 50px;
      --gap: 5px;
    }
    
    .container {
      column-width: var(--box-width);
      column-gap: var(--gap);
      width: 200px;
      border: 2px solid #000;
      padding: 10px;
    }
    
    .box {
      width: var(--box-width);
      height: var(--box-height);
      background-color: orange;
      margin-bottom: var(--gap);
    }
    <div class="container">
      <div class="box">1</div>
      <div class="box">2</div>
      <div class="box">3</div>
      <div class="box">4</div>
      <div class="box">5</div>
      <div class="box">6</div>
      <div class="box">7</div>
      <div class="box">8</div>
    </div>