Implementing children-count() using Modern CSS
We can get the number of siblings using sibling-count() but we cannot get the number of children yet. There is a proposal for a children-count() function, but until we get an official release, we can hack it using Scroll-Driven Animations.
First, you add an extra element inside your container (That's one drawback of the method)
<div class="container">
<!-- Your content -->
<n></n> <!-- the extra element -->
</div>
Then you make its width equal to the number of siblings multiplied by 1px
.container > n {
position: absolute;
width: calc((sibling-count() - 1)*1px);
/* -1 is used to exclude our extra element from the count */
}
Finally, we apply a trick from a previous post (Get the width & height of any element without JavaScript) to get the width of that element and transfer it to the parent element.
@property --_n {syntax: "<number>";inherits: false;initial-value: 0;}
.container {
timeline-scope: --n;
animation: --n linear both;
animation-timeline: --n;
animation-range: entry 100% exit;
--n: round(1/(var(--_n))); /* --n: children-count() */
}
@keyframes --n {0% {--_n: 1}}
.container > n {
position: absolute;
overflow: auto;
width: calc((sibling-count() - 1)*1px);
}
.container > n:before {
content: "";
display: block;
width: 1px;
view-timeline: --n x;
}
A useful trick to display the count of some hidden content
See the Pen children-count() using pure CSS by Temani Afif (@t_afif) on CodePen.
Or to have dynamic grid layouts (inspired by kizu.dev/tree-counting-and-random/#square-ish-layout)
See the Pen Square-ish layout by Temani Afif (@t_afif) on CodePen.
⚠️ A very hacky method to use with caution ⚠️
More CSS Tips
- Complex border-only Shapes with Gradient Coloration Using border-shape with border-area to easily create border-only shapes.
- Dynamic Node Connection (CSS-only Diagram) II More node connections using border-shape and modern CSS.