DEV Community

Kevin Pennekamp
Kevin Pennekamp

Posted on • Originally published at crinkles.dev

A nth-child CSS trick

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 use. But still, it is a cool trick. For me, the latest of these tricks is setting a CSS custom property value, corresponding with the :nth-child value. Why? Because now we can use the --nth-child custom property inside calc() functions.

But why not use X?

Sure, in most, if not all, of my projects I use SCSS instead of CSS. But CSS is getting more and more features, making SCSS redundant for me. Looking at you CSS nesting. With each trick or implementation, you can remove another dependency on SCSS, and go back to plain CSS. Using @for-loops makes it easy to achieve the same result. But you will generate roughly the same CSS selector several times.

You might also think using :nth-child(n) would allow you to achieve the same, without all the custom properties. Unfortunately, the n is not useable in the calc() function. So, we use custom properties.

How to set it up

On the highest level of your CSS, you define a list like the one below. This results in all elements having access to a --nth-child custom property. At least as long as you don’t exceed the length of your list.

:nth-child(1) { --nth-child: 1 }
:nth-child(2) { --nth-child: 2 }
:nth-child(3) { --nth-child: 3 }
:nth-child(4) { --nth-child: 4 }
:nth-child(5) { --nth-child: 5 }
Enter fullscreen mode Exit fullscreen mode

What can we do with this trick?

Glad you asked! In the last few years, I came across two use cases. Two, whole, use cases. In the latest use case, I wanted to automatically generate a color palette. Not to match a branding of a company. But to automatically populate different series of data in a chart. With this trick, we can do that with a single line.

background-color: hsl(calc(100 * var(--nth-child)) 100% 40%);
Enter fullscreen mode Exit fullscreen mode

In an earlier use case, I replicated the UI implementation of toasts from Vercel. On the link, you see a list of toast messages stacked with a little bit of perspective. I originally used an SCSS implementation, looking like the snippet below. Note it uses :nth-last-of-type, given the reversed order and bottom orientation. But the general idea remains the same.

@for $i from 1 through 20 {
    &:nth-of-type(#{$i}) {
      opacity: 1 - 0.15 * ($i - 1);
      transform:
          translate3d(50%, 0 - (5 * ($i - 1)) + px, -1 * $i + px) 
          scale(1 - (0.05 * ($i - 1)));
    }
}
Enter fullscreen mode Exit fullscreen mode

This would create twenty different CSS selectors, all with a different value for $i. But using this little trick, we can reduce the code, and make it more maintainable in the process.

.class {
    /* We want to start counting at 0 */
    --v: var(--nth-last-child) - 1;
    opacity: 1 - calc(var(--v) * 0.15);
    transform:
        translate3d(
            50%, 
            calc(-5px * var(--v)), 
            calc(-1px * var(--v)) 
        scale(calc(1 - var(--v) * 0.05);
}
Enter fullscreen mode Exit fullscreen mode

That was it. That was my latest CSS trick.

Top comments (4)

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