|<<>>|6 of 293 Show listMobile Mode

CSS Magician Roman Komarov plays with sibling-count and sibling-index

Published by marco on

The article Possible Future CSS: Tree-Counting Functions and Random Values by Roman Komarov (Kizu.Dev) 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 CSS Values and Units Module Level 5 (w3C).

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.

 Stacking and squaring up grid items

Here’s a taste of the code for getting a random value in CSS,

.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)
    );
  }
}

You should really see the original article 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 square with random transforms and coloring. Finally, he even stacks them, 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 Ana Tudor’s many examples or Una Kravets’s radial menu, or Amit Sheen’s demos.