sibling-count()
The sibling-count() function returns the total number of sibling elements an element has, including itself.
Comparison
It can be an equivalent to JavaScript DOM manipulation element.parentElement.children.length
const element = document.querySelector('.page-wrap');
console.log(element?.parentElement?.children.length ?? 0);
// expected output: a whole number or zero
In the previous example .page-wrap isn't the parent, it's the starting element.
The equivalence
Anyway, as I said sibling-count() returns an integer representing the total of sibling DOM elements (direct children of the parent) of the element on witch it´s used, including itself. That´s exactly what our JS code logs.
So for .page-wrap:
.page-wrap {
/* same integer JavaScript console.log prints */
--count: sibling-count();
}
Where they differ
Reactivity. This is the big one. JS code reads the DOM once at execution time. If a sibling gets added or removed later, the logged value is stale, so we need a MutationObserver or a manual re-run.
The sibling-count() function is a live computed value: the browser recalculates it as part of style resolution, so it's always current with zero JS.
Syntax
<sibling-count()> = sibling-count()
The sibling-count() function takes no arguments an returns an <integer>.
Uses cases
For reverse staggered transitions combine with sibling-index(). This way you make the last item animate first and the last item animate last.
.item { transition-duration: calc((sibling-count() - sibling-index() + 1) * 200ms); }
Imagine you are rendering a bunch of tags. With sibling-count() you automatically adjust the font size based on how many tags there are: more tags equals smaller text, and fewer tags equals bigger text.
.tag { font-size: calc(3rem - (sibling-count() * 0.1rem)); }