Get Grid Information using pure CSS
Thanks to modern CSS, it's now easy to retrieve various information from a responsive CSS grid such as the number of rows, number of columns, and the coordinates of each item within the grid. The only requirement is to have equal-width columns. Rows can have different heights.
.container {
--s: 120px; /* column size */
--g: 10px; /* gap */
display: grid;
grid-template-columns: repeat(auto-fill,minmax(var(--s),1fr));
gap: var(--g);
container-type: inline-size; /* to be able to use 100cqw */
}
.container > * {
/* number of columns */
--n: round(down,(100cqw + var(--g))/(var(--s) + var(--g)));
/* number of rows */
--m: round(up,sibling-count()/var(--n));
/* item coordinates */
--x: round(down,(sibling-index() - 1)/var(--n)); /* row index */
--y: mod(sibling-index() - 1,var(--n)); /* column index */
}
Here is an interactive demo where each item shows all the information it gets. You can resize to notice the responsive behavior where all the values adjust in real time.
See the Pen Grid information (chrome-only) by Temani Afif (@t_afif) on CodePen.
If you combine this with the new if(), you can easily create conditional styling.
Color elements in a specific row
.container > * {
background: if(style(--x = 3): red;)
}
Or specific column
.container > * {
background: if(style(--y = 2): red;)
}
Or both:
.container > * {
background: if(style((--x = 3) or (--y = 2)): red;)
}
See the Pen Row/columns selection by Temani Afif (@t_afif) on CodePen.
We can have more complex conditions and combine them all:
.container > * {
background: if(
style((--y = calc(var(--n) - 1)) and (--x = 0)): red; /* last element of first row */
style((--x = calc(var(--m) - 1))): green; /* last row */
style(--x = --y): orange; /* the diagonal */
)
}
See the Pen Random grid selection by Temani Afif (@t_afif) on CodePen.
More CSS Tips
- Dynamic Node Connection (CSS-only Diagram) II More node connections using border-shape and modern CSS.
- Get Grid Information using pure CSS II Retrieving the position of randomly placed items using only CSS.
- A New Way to Round the Corners of CSS Shapes Learn how to round the corners of any shape with a simple code.
- Responsive ASCII Arts using text-fit Thanks to a new CSS property, it's now easy to create responsive ASCII art.