Search code examples
javascripthtmlcsscss-grid

Two columns grid with flat mixed list of items


I'm trying to make two columns layout of flat list of random items where some should be on the left one under each other and others on the right.

So far i'm using css grid but i have an issue with "empty rows" because those cells do not know to "start from top".

If i add all of them grid-row-start: 1, they all just collapses above each other at the top.

I don't want to change structure of the container as i'd like to just shuffle the classes to move items. In theory i can add class like row-1, row-2 etc in JavaScript and use it to determine where the cell should start but I wonder if there is an cleaner way to approach this purely in css.

Demo: https://jsfiddle.net/mbynw4cL/1/

enter image description here


Solution

  • So what you want is to use the grid-auto-flow property:

    .grid {
      width: 200px;
      border: 1px solid green;
      display: grid;
      grid-template-columns: auto auto;
      grid-auto-flow: dense;
    }
    
    .item {
      width: 30px;
      height: 30px;
      margin: 5px;
    }
    
    .item.left {
      grid-column-start: 1;
      justify-self: start;
      background: red;
    }
    
    .item.right {
      grid-column-start: 2;
      justify-self: end;
      background: blue;
    }
    <div class="grid">
      <div class="item left"></div>
      <div class="item left"></div>
      <div class="item right"></div>
      <div class="item right"></div>
      <div class="item left"></div>
    </div>

    This will "fill in" the gaps.

    See https://css-tricks.com/snippets/css/complete-guide-grid/#article-header-id-25 for more on CSS grid.