grid-auto-flow in snake lines?
Solution 1:
Here is an idea if we consider the fact that you will always have 3 rows:
.container {
display:grid;
grid-template-rows:20px 20px 20px;
grid-auto-columns:20px;
grid-auto-flow:column dense;
}
.container > div:nth-child(6n + 4) { grid-row:3; }
.container > div:nth-child(6n + 5) { grid-row:2; }
/*.container > div:nth-child(6n + 6) { grid-row:1; } to illustrate the pattern but not needed */
/* Irrelevant styles */
.container {
grid-gap:5px;
counter-reset:num;
margin:10px;
}
.container > div {
border:1px solid;
}
.container > div:before{
content:counter(num);
counter-increment:num;
}
<div class="container">
<div></div><div></div><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 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></div><div></div><div></div>
</div>
That you can easily extend to 4 rows or any number:
.container {
display:grid;
grid-template-rows:repeat(4,20px);
grid-auto-columns:20px;
grid-auto-flow:column dense;
}
.container > div:nth-child(8n + 5) { grid-row:4; }
.container > div:nth-child(8n + 6) { grid-row:3; }
.container > div:nth-child(8n + 7) { grid-row:2; }
/*.container > div:nth-child(8n + 8) { grid-row:1; }*/
/* For N = number of rows
.container > div:nth-child((2xN)n + (N+1)) { grid-row:N; }
.container > div:nth-child((2xN)n + (N+2)) { grid-row:(N-1); }
....
.container > div:nth-child((2xN)n + (2xN)) { grid-row:1; }
*/
.container {
grid-gap:5px;
counter-reset:num;
margin:10px;
}
.container > div {
border:1px solid;
}
.container > div:before{
content:counter(num);
counter-increment:num;
}
<div class="container">
<div></div><div></div><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 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></div><div></div><div></div>
</div>