Search code examples
csscss-grid

Fixed number of columns with grid-auto-flow: column


I need to make a grid layout that has exactly four columns and orders the elements down instead of right. Here's my starting point:

.wrapper {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-flow: column;
}
.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
}
.box:nth-child(even) {
  background-color: #ccc;
  color: #000;
}
<div class="wrapper">
  <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 class="box">9</div>
  <div class="box">10</div>
  <div class="box">11</div>
  <div class="box">12</div>
</div>

Expected output is

1  5  9
2  6  10
3  7  11
4  8  12

If a 13th element is added, either is acceptable:

1  6  11           1  6  10
2  7  12           2  7  11
3  8  13     or    3  8  12
4  9               4  9  13
5  10              5

If only three divs were present then I would expect

1  2  3

Using something besides display: grid is OK too, though I can't change the markup much.


Solution

  • You can use column-count: 3; instead of display: grid and add display: inline-block to the child elements.

    .wrapper {
      column-count: 3;
    }
    
    .box {
      background-color: #444;
      color: #fff;
      border-radius: 5px;
      padding: 20px;
      font-size: 150%;
      display: inline-block;
      width: 100%;
      margin: 5px;
      box-sizing: border-box;
    }
    
    .box:nth-child(even) {
      background-color: #ccc;
      color: #000;
    }
    <div class="wrapper">
      <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 class="box">9</div>
      <div class="box">10</div>
      <div class="box">11</div>
      <div class="box">12</div>
      <div class="box">13</div>
    </div>