'Incomplete CSS grid leaving first item blank instead of last

I want to display an unknown number of items in a 3 column grid. CSS grid seems like the perfect solution and using it in its simplest form gives me 99% of what I'm looking for.

However! If I have 8 items, it will leave the first spot in row 1 empty and fill the rest of the grid. Example:

grid with first item empty

Instead, I want it to fill the first row and leave the final spot in the grid empty like this:

grid with last item empty

The CSS I'm using is:

.modules {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

The HTML is:

<div class="row modules">
  <div class="module">
  </div>
  ...
  <div class="module">
  </div>
</div>

Is there a way to specify this behaviour or would it be simpler to switch to Flexbox?



Solution 1:[1]

Ok, I found out what the issue was. There is an interaction between the grid layout and the content property that had an unexpected effect.

This CSS (used throughout the project I'm working on) resulted in the behaviour I was seeing:

.row:before,
.row:after {
  content: "";
}

Changing it to negate this property setting in this particular case reverted the behaviour to the default CSS grid behaviour that I was expecting:

.row:before,
.row:after {
  content: none;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1