This page shows the source for this entry, with WebCore formatting language tags and attributes highlighted.

Title

CSS Magician Roman Komarov plays with <c>sibling-count</c> and <c>sibling-index</c>

Description

The article <a href="https://kizu.dev/tree-counting-and-random/" author="Roman Komarov" source="Kizu.Dev">Possible Future CSS: Tree-Counting Functions and Random Values</a> is another mathematical master class in using CSS variables and calculations to get at values like "sibling count" and "sibling index", two values that are in a future proposal for <a href="https://www.w3.org/TR/css-values-5/#tree-counting" source="w3C">CSS Values and Units Module Level 5</a>. The final demo looks like this, with randomly laid out items squared up into equal columns and rows where possible, all done with only CSS. <img src="{att_link}stacking_and_squaring_up_grid_items.jpg" href="{att_link}stacking_and_squaring_up_grid_items.jpg" align="none" caption="Stacking and squaring up grid items" scale="40%"> Here's a taste of the code for getting a random value in CSS, <code><macro convert="-all">.random-example { & li { --random-part-from-sibling: pow(var(--sibling-index), 3) - pow(var(--sibling-index), 2) + var(--sibling-index); --random-part-from-count: var(--children-count); --random-limit: var(--closest-prime); --random-value: calc( mod( var(--random-part-from-sibling) * var(--random-part-from-count) * var(--seed, 0) , var(--random-limit) ) / var(--random-limit) ); } }</code><macro convert="+all"> You should really see the <a href="https://kizu.dev/tree-counting-and-random/">original article</a> for the interactive demos. As always, it's stunning how quickly the browser CSS and layout engine efficiently updates values, invalidating only the parts that are affected, even with deeply nested calculations. I went through the article in Opera Beta on an M1 MacBook Pro (from 2020), with a relatively new version of Chromium and it was smooth as silk, with no CPU spikes and no sluggishness (as Komarov indicated might happen in Safari). He first defines the sibling-count and sibling-index functions, then builds randomness on top of those. He uses this toolkit to build grids that know how many items they have so that he can keep the grid <a href="https://kizu.dev/tree-counting-and-random/#square-ish-layout">a square</a> with random transforms and coloring. Finally, he even <a href="https://kizu.dev/tree-counting-and-random/#stacking">stacks them</a>, with random overlapping and z-order control. Finally, he links some amazing CSS demos where people built things that could use this functionality in CSS (but have had to make do with JS for now). See <a href="https://codepen.io/thebabydino/pens/popular">Ana Tudor's many examples</a> or <a href="https://una.im/radial-menu/">Una Kravets's radial menu</a>, or <a href="https://codepen.io/amit_sheen/pens/popular">Amit Sheen's demos</a>.