Nicofisi
Nicofisi

Reputation: 1113

Issue with how the elements are placed in rows in the CSS Grid Layout

I'm trying to solve a grid problem with how the elements are automatically placed in the rows not in the way I intend them to. The code is the simplest possible variation written to demonstrate the issue. The number of paragraphs is variable-length, there can be any amount of them.

div {
  display: grid;
  grid-template-columns: repeat(2, 1fr);

}

p:nth-child(4n + 1) {
  grid-column: 1 / span 1;
}

p:nth-child(4n + 2) {
  grid-column: 2 / span 1;
}

p:nth-child(4n + 3) {
  grid-column: 2 / span 1;
}

p:nth-child(4n) {
  grid-column: 1 / span 1;
}
<div>
  <p>Test1</p>
  <p>Test2</p>
  <p>Test3</p>
  <p>Test4</p>
  <p>Test5</p>
  <p>Test6</p>
  <p>Test7</p>
  <p>Test8</p>
  <p>Test9</p>
  <p>Test10</p>
</div>

Here is the current result, with two arrows showing what I want to achieve: Current

And here is exactly what I want to achieve, created for presentation purposes by just reordering HTML elements in a basic grid: What I want

Thank you in advance!

Upvotes: 1

Views: 152

Answers (1)

Charlie Harding
Charlie Harding

Reputation: 685

This can be solved with the grid-auto-flow: dense CSS rule on the grid parent. This has the effect that previously blank cells will be filled, rather than searching for the next available space.

Upvotes: 2

Related Questions