DEV Community

Muneeb Ali
Muneeb Ali

Posted on

Goodbye :nth-child! How Modern CSS sibling-index() Works Under the Hood

Ever found yourself writing endless lines of :nth-child(1), :nth-child(2), :nth-child(3) or injecting custom CSS variables via JavaScript just to stagger a list of entrance animations?

Modern CSS (Values & Units Module Level 5) introduces two native functions:

  • sibling-index() — Returns the 1-based index of the element among its siblings.
  • sibling-count() — Returns the total count of siblings under the parent.

Here is the complete video breakdown and live animation:

1. Staggered Delays in Pure CSS

.card {
  animation: cardFadeIn 0.6s cubic-bezier(0.16, 1, 0.3, 1) both;
  animation-delay: calc(sibling-index() * 120ms);
}
Enter fullscreen mode Exit fullscreen mode

2. Dynamic 360° Color Wheels with OKLCH

.chip {
  --hue: calc((sibling-index() / sibling-count()) * 360deg);
  background: oklch(0.68 0.22 var(--hue));
}
Enter fullscreen mode Exit fullscreen mode

3. Reverse z-Index Overlapping Avatars

.avatar {
  margin-left: -14px;
  z-index: calc(sibling-count() - sibling-index() + 1);
}
Enter fullscreen mode Exit fullscreen mode

🎯 60-Second Challenge: Can You Solve It?

Can you write a single calc() formula so the middle item in an odd list of bars gets the largest height/scale?

Download the starter HTML file and test your formula:

Top comments (0)