Search code examples
htmlcsscss-grid

How to place elements with same class on a column and different rows with css grid?


I have a question "choice/match" and I need to put choices in a column and matches in an other column with grid css, my problem is the match column is overlapping.

This is how it looks like right now :

.grid{
  display:grid; 
  grid-template-columns: 1fr 1fr;
  gap:12px;
}

.grid>div{
  padding:12px;
  margin:0;
  color:#fff;
  background:#222;
}

.choice{
  grid-column-start: 1;
}
.match{
  grid-column-start:2;
  grid-row-start:1;
}
<div class="grid">
 <div class="choice">Choice 1</div>
 <div class="choice">Choice 2</div>
 <div class="choice">Choice 3</div>
 <div class="match">Match 1</div>
 <div class="match">Match 2</div>
 <div class="match">Match 3</div>
</div>

If I remove grid-row-start it starts from the second line.
FIY this is just an example, the question have a dynamic equal number of matches and columns.


Solution

  • Add grid-auto-flow: dense

    .grid{
      display:grid; 
      grid-template-columns: 1fr 1fr;
      grid-auto-flow: dense;
      gap:12px;
    }
    
    .grid>div{
      padding:12px;
      margin:0;
      color:#fff;
      background:#222;
    }
    
    .choice{
      grid-column-start: 1;
    }
    .match{
      grid-column-start:2;
    }
    <div class="grid">
     <div class="choice">Choice 1</div>
     <div class="choice">Choice 2</div>
     <div class="choice">Choice 3</div>
     <div class="match">Match 1</div>
     <div class="match">Match 2</div>
     <div class="match">Match 3</div>
    </div>