Get the index of an element within its parent
With CSS, you can use the new sibling-index()
function to get the position of any element relative to all its sibling elements. You can also rely on sibling-count()
to get the number of siblings.
The results are also available within pseudo-elements.
<div class="container">
<div></div>
<div></div>
<div></div>
...
</div>
.container div {
border: calc(sibling-index()*2px) solid;
opacity: calc(sibling-index()/sibling-count());
}
.container div::before {
content: counter(i) "/" counter(N);
counter-reset: N sibling-count() i sibling-index() /* they refer to the div element */
}
See the Pen sibling-index() / sibling-count() by Temani Afif (@t_afif) on CodePen.
The functions are a bit verbose, so we can create our custom functions and write less code.
@function --N() {
result: sibling-count();
}
@function --i() {
result: calc(sibling-index() - 1); /* we can change and start from 0 instead of 1 */
}
.container div {
border: calc(--i()*2px) solid;
opacity: calc(--i()/--N());
}
.container div::before {
content: counter(i) "/" counter(N);
counter-reset: N --N() i --i()
}
See the Pen sibling-index() / sibling-count() + custom functions by Temani Afif (@t_afif) on CodePen.
⚠️ Limited support (Chrome only for now) ⚠️
More CSS Tips
- Dots loader using shape() A classic 3 dots loader created using the new shape().
- The future of hexagon shapes A new way to easily create hexagon shapes using corner-shape.