Amir hossein Karimi
Amir hossein Karimi

Reputation: 127

CSS grid with repeated rows and fixed column via row flow

I want to create a grid like this:

1 5
2 6
3 7
4 8
9 
10

The logic is first fill 4 rows of first column and then fill the second column, if there is more cell fill them from 5th row, also fill 4 rows of first column and then second.

for example:

1
2
3

1 5
2 6
3
4

1   5
2   6
3   7
4   8
9   13
10  14
11
12

Upvotes: 0

Views: 44

Answers (1)

Temani Afif
Temani Afif

Reputation: 272816

You can do it like below:

.container {
  display:inline-grid;
  grid-auto-columns:50px; /* column width, not mandatory you can keep it default */
  grid-auto-flow:dense; /* make sure to fill all the cells */
  grid-gap:5px;
  margin:10px;
  counter-reset:num;
}

.container div {
  grid-column:1; /* first column by default */
  border:1px solid red;
}

/* from 5 to 8 and each 8 elements, put on second column*/
.container div:nth-child(8n + 5),
.container div:nth-child(8n + 6),
.container div:nth-child(8n + 7),
.container div:nth-child(8n + 8){
  grid-column:2;
}
/**/

.container div::before {
  content:counter(num);
  counter-increment:num;
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
</div>

<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>


<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

Upvotes: 1

Related Questions