Snake-Line Grids with CSS Grid
Query: Is it feasible to generate snake-like cell patterns within a column-oriented CSS grid, similar to the example below?
01 06 07 12 02 05 08 11 03 04 09 10
Solution:
Assuming that the grid will always have three rows, here's a clever solution:
<code class="css">.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; } /* Cosmetic styles */ .container { grid-gap: 5px; counter-reset: num; margin: 10px; } .container > div { border: 1px solid; } .container > div:before { content: counter(num); counter-increment: num; }</code>
The key to this solution is the nth-child() selector, which selects child elements based on their position within their parent. The grid-auto-flow: column dense is what keeps the element in a dense formation of columns.
This technique is especially useful when you want the flexibility of a snake-like fill pattern but without having to define every single cell's position manually.
The above is the detailed content of Can CSS GridQuery Create Snake-Like Cell Patterns in Column-Oriented Grids?. For more information, please follow other related articles on the PHP Chinese website!