Advanced Tree Counting: Mathematical Layouts With sibling-index() And sibling-count() - Smashing Magazine
Briefly

Advanced Tree Counting: Mathematical Layouts With sibling-index() And sibling-count() - Smashing Magazine
Sibling-index() and sibling-count() enable staggered cascade animation timing directly from the DOM structure. The approach avoids generating many :nth-child() selectors or hardcoding per-position variables. It also avoids injecting inline CSS variables via JavaScript, which can couple styling to DOM manipulation and break during refactors. The method leverages information the browser already has about element order and total siblings, so delays can be calculated with CSS variables and arithmetic. It scales from small lists to very large numbers of items without needing build-time selector generation or runtime style updates.
"Meet sibling-index() and sibling-count(). Staggered cascade effect in one line of CSS without :nth-child() rules or JS workarounds. Works for 5 items or 5,000."
"Because the options were always the same. Say you want staggered animation delays on a list of 10 items. You either wrote a Sass loop that spat out a dozen :nth-child() rules, each one hardcoding a --index variable for that specific position: /* One rule per item. Hope the list never grows. */ li:nth-child(1) { --idx: 1; } li:nth-child(2) { --idx: 2; } li:nth-child(3) { --idx: 3; } /* ... eight more of these ... */ li:nth-child(10) { --idx: 10; } li { animation-delay: calc(var(--idx) * 100ms); }"
"Or you looped through elements in JavaScript and set inline styles. style="--index: 3". Right there in the DOM. Works fine. Also spreads layout concerns across your scripts and quietly breaks six months later when someone refactors the component without realizing the CSS depends on a JavaScript-injected variable."
"Both approaches have always bugged me for the same reason: you're telling the browser something it already knows. The browser built the DOM tree. It knows which element is the third child. It has"
Read at Smashing Magazine
Unable to calculate read time
[
|
]