Modern CSS functions like round(), sibling-count(), and sibling-index() can be combined with container queries to compute a CSS grid's number of columns, number of rows, and each item's row/column coordinates, using pure CSS with no JavaScript. This requires equal-width columns, though row heights can vary. An interactive demo shows the values updating live as the grid resizes. The technique currently only works in Chromium-based browsers, and can be paired with the new if() function for conditional styling.

1m read timeFrom css-tip.com
Post cover image

Questions this post answers

How can I get the number of rows and columns of a CSS grid without JavaScript?

Use the CSS round() function together with sibling-count() and container queries. Define --n as round(down,(100cqw + gap)/(column-size + gap)) for column count, and --m as round(up, sibling-count()/var(--n)) for row count. This requires equal-width columns, though rows can have different heights, and currently works only in Chromium-based browsers. daily.dev surfaces practical CSS tricks like this for developers building responsive grid layouts.

How do I find the row and column index of a specific item inside a CSS grid using CSS only?

Calculate the row index with round(down,(sibling-index() - 1)/var(--n)) and the column index with mod(sibling-index() - 1, var(--n)), where --n is the number of columns. These rely on the sibling-index() and sibling-count() CSS functions plus container queries, and are currently limited to Chromium-based browsers. Developers experimenting with cutting-edge CSS features track browser support gaps on daily.dev.

77.2K Impressions3 Comments