Search code examples
cssflexboxcss-grid

Place items in pairs in two rows using css grid


I'm trying to render items in a specific order, look at the picture: enter image description here

i.e. there is an infinite number of items, by columns, each column has two items. Do you have any ideas how to code this using grids or flexbox or any other way (maybe by combining them)? I know I can do it with tables, but I'm trying to avoid them this time.


Solution

  • nth-child() can help here

    .box {
      display:grid;
      grid-auto-flow:column dense; /* column flow with "dense" to fill all the cells */
      grid-template-rows:50px 50px; /* 2 rows */
      grid-auto-columns:50px;
    }
    .box span:nth-child(4n + 2) { /* this will do the trick*/
       grid-row:1; /* we make 2 in the first row and 3 will be pushed to second row */
    }
    
    /* irrelevant styles */
    .box {
      counter-reset:num;
      grid-gap:5px;
    
    }
    .box span {
      background:yellow;
      font-size:25px;
    }
    
    .box span::before {
      content:counter(num);
      counter-increment:num;
    }
    <div class="box">
     <span></span>
     <span></span>
     <span></span>
     <span></span>
     <span></span>
     <span></span>
     <span></span>
     <span></span>
     <span></span>
     <span></span>
     <span></span>
     <span></span>
     <span></span>
     <span></span>
     <span></span>
     <span></span>
    </div>