DEV Community

A nth-child CSS trick

Kevin Pennekamp on January 25, 2023

Sometimes you figure out a cool trick that just feels so powerful. It opens you up to a range of new possibilities. That you, quite frankly, rarely...
Collapse
 
gilfewster profile image
Gil Fewster

Nice trick, although the finite list length makes me twitch a bit!

This is one of those times where I wish you could use the css counter() value as a number type. Then you could do something like this:

.count-children {
    counter-reset: children;
}

.count-children > * {
    counter-increment: children;
    --nth-child: counter(children);
}

.swatch {
    background: hsl(calc(100 + var(--nth-child)) 100% 40%);
}
Enter fullscreen mode Exit fullscreen mode

I wonder if you could do something clever with Houdini to make something like this work.

Collapse
 
vyckes profile image
Kevin Pennekamp

Yeah using counter() would actually be the icing on the cake. Given all other options (like reset etc), that would really work well.

Curious about Houdini, might dive into it a bit to see if we can get something to work. Nice suggestion!

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Is there a mistake in the last example? Should --nth-last-child be --nth-child?

Also, why bother with --v? Could you not just set the --nth-child vars up as zero based in the first place? Or maybe call it --child-index for clarity?

Nice trick though! 👍

Collapse
 
vyckes profile image
Kevin Pennekamp

You are right, in a sense. As the list use case is reversed, I am using --nth-last-child (without setting it somewhere). But they work the same way, list different starting point of counting.

--v I use just to make the code-snippet a little bit more readable on sites like this. --child-index might actually be a good name