css-grid

How to organize items on css grid with an uneven number of items in each column


I want to organize items top to bottom on a css grid with each column containing any number of items, but when I try to put elements on the next column they don't start at the top of the grid, instead they stay on the same row as the previous item. How can I fix that?

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 3 columns with equal width */
  gap: 10px; /* Space between grid items */
}

.column-1 {
  grid-column: 1;
}

.column-2 {
  grid-column: 2;
}

.column-3 {
  grid-column: 3;
}

.grid-item {
  background-color: lightblue;
  padding: 10px;
  border: 1px solid #000;
  text-align: center;
}
<div class="grid-container">
    <div class="grid-item column-1">Item 1.1</div>
    <div class="grid-item column-1">Item 1.2</div>
    <div class="grid-item column-1">Item 1.3</div>
    <div class="grid-item column-2">Item 2.1</div>
    <div class="grid-item column-2">Item 2.2<br>foo</div>
    <div class="grid-item column-2">Item 2.3<br>foo</div>
    <div class="grid-item column-2">Item 2.4</div>
    <div class="grid-item column-2">Item 2.5</div>
    <div class="grid-item column-3">Item 3.1</div>
    <div class="grid-item column-3">Item 3.2</div>
  </div>


Solution

  • You are missing one property to tell grid that you want to actually fill the column. It's called grid-auto-flow

    From mdn docs

    The grid-auto-flow CSS property controls how the auto-placement algorithm works, specifying exactly how auto-placed items get flowed into the grid.

    ...

    column

    Items are placed by filling each column in turn, adding new columns as necessary.

    So just add grid-auto-flow: column; property to .grid-container class.

    .grid-container {
      display: grid;
      grid-auto-flow: column; /* SOLUTION */
      grid-template-columns: repeat(3, 1fr); /* 3 columns with equal width */
      gap: 10px; /* Space between grid items */
    }
    
    .column-1 {
      grid-column: 1;
    }
    
    .column-2 {
      grid-column: 2;
    }
    
    .column-3 {
      grid-column: 3;
    }
    
    .grid-item {
      background-color: lightblue;
      padding: 10px;
      border: 1px solid #000;
      text-align: center;
    }
    <div class="grid-container">
        <div class="grid-item column-1">Item 1.1</div>
        <div class="grid-item column-1">Item 1.2</div>
        <div class="grid-item column-1">Item 1.3</div>
        <div class="grid-item column-2">Item 2.1</div>
        <div class="grid-item column-2">Item 2.2<br>foo</div>
        <div class="grid-item column-2">Item 2.3<br>foo</div>
        <div class="grid-item column-2">Item 2.4</div>
        <div class="grid-item column-2">Item 2.5</div>
        <div class="grid-item column-3">Item 3.1</div>
        <div class="grid-item column-3">Item 3.2</div>
      </div>