Search code examples
csscss-grid

CSS Grid Items are not aligned side by side


I have a list of 11 items I need to end up separated into two side by side lists, with them advancing vertically instead of horizontally so that I end up with items 1 through 5 stacked vertically in the left column and items 6 to 10 stacked on the right side.

Here is my SCSS for the grid and items:

.no-list-grid {
  counter-reset: nolist;
  display: grid;
  gap: 30px;
  grid-template-columns: repeat(4, 1fr);
}
.no-list-item {
  padding: 30px;
  background: #eeee;
  grid-column-start: 3;
  grid-column-end: 5;
  &:first-child,
  &:nth-child(2),
  &:nth-child(3),
  &:nth-child(4),
  &:nth-child(5) {
    grid-column-start: 1;
    grid-column-end: 3;
  }
}

I have a code pen setup here with an expanded example: https://codepen.io/zoladesigners/pen/MWXOPPm

You can see each column of the grid ends up the correct width but they are not aligned next to each other.

If any other information would be helpful please let me know, I appreciate any solutions anyone has, thank you!


Solution

  • I would change the grid-auto-flow to column so it fills by column first instead of row and then it should all match up without needing to position each element. You will need to specify the total number of rows. CodePen.

    .no-list-grid {
      counter-reset: nolist;
      display: grid;
      gap: 30px;
      grid-template-rows: repeat(6, 1fr);
      grid-auto-flow: column;
    }
    
    .filler {
      grid-row-start: 1;
      grid-row-end: 2;
      grid-column-start: 2;
      grid-column-end: 3;
    }
    .no-list-item {
      padding: 30px;
      background: #eeee;
    }
    
    .no-list-count {
      counter-increment: nolist;
    }
    
    .no-list-item.no-list-count {
      display: flex;
      gap: 1em;
      &:before {
        content: counter(nolist);
        display: flex;
        justify-content: center;
        align-items: center;
        flex-shrink: 0;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        border: 1px solid blue;
        font-size: 24px;
        color: teal;
      }
    }
    

    Then add a div with the class filler anywhere in the list.

      <div class="filler"></div>