How to find specific items in lists at intervals

Matthew Croak
Sep 10 · 6 min read
Photo by Greg Rakozy on Unsplash

nth-child is a selector that matches every nth child element of its parent. Say you want to apply CSS to only a specific number of p elements. nth-child is exactly what you need.

#nameContainer p {
color: black;
}
#nameContainer:hover p:nth-child(1) {
color: red;
}

The above CSS will change the color of only the first p when the user hovers over nameContainer.


Other Options That Can Be Passed to nth-child

odd

By using nth-child(odd), you can apply CSS to every odd child element. If you were to rewrite the CSS above to affect every odd element, the p tag for Kelly, Stanley, Michael, and so on would turn red.

even

Conversely, nth-child(even) would apply CSS to Creed, Oscar, Jim, etc.

formula (an + b)

In addition to the value n being able to be any number, you can also use a formula. nth-child(3n) would affect every third child element. nth-child(3n+1) would apply to every third element starting from the first one. Multiplication and division are not supported in nth-child(n) formulas. Let’s break down this formula format and see what each part means to nth-child.

a represents the cycle size. If a is equal to 3, that means that the CSS is applied to every third element. See below for p:nth-child(3n).

n is the counter used to determine which sibling element among the group is affected. By itself, it refers to every child element. p:nth-child(n) would select every p. This is a bit redundant as you could simply use p by itself.

b represents the offset value. If you look back to the earlier example nth-child(3n+1), the CSS would be applied to every third element, initially offset by one. So for p:nth-child(3n + 1) the first p tag would be affected and then every third tag. See below.

As you can see, every third p tag is affected; the iteration starts after the first.

You can also use subtraction. In nth-child(3n-1), the cycle is 3, and n is the counter, implying every third p tag would be affected. But, when the offset is -1, which is essentially 3n+(-1), you would start your cycle at one element before the first p tag. See below.

Every third p tag, starting with the second due to -1 offset

Now that you understand the formulaic option for nth-child, let’s check out the reverse operation, negative child range.


Negative Child Range

The negative child range is useful when you want to accomplish what you would with formulaic nth-child but in reverse order. You simply put a minus sign in front of an nth-child formula. See below.

p:nth-child(-2n+5){
color: red;
}

Given our list of “Office” characters, this nth-child negative range will apply CSS to the names, starting with Michael, as it is the fifth name on the list, then work backwards, selecting every second name. The CSS above would make Michael, Stanley, and Kelly red. This negative range selection works similarly to an nth selection for child elements called nth-last-child(n).


Combined Child Ranges

With combined child ranges, you can apply multiple nth-child selectors to one group of siblings. Say you want to get all child elements between the first and the fifth. You can accomplish this by writing a combined nth-child selection. See below.

p:nth-child(n+5):nth-child(-n+10){
color: red;
}

Here we have combined two nth-child selectors to grab all p tags between the fifth and tenth tags. The first selector will grab all p tags starting from the fifth one, Michael, as 5 is the offset. Then we add on a negative child range to work backwards from the tenth, Dwight. The above would make the names from and including Michael to Dwight red. By writing a negative child range in this format, you can replicate the same behavior as another child selector, nth-last-child.


nth-last-child(n)

nth-last-child(n) works the same as nth-child(n), only it starts from the end of the group of siblings, not the beginning. nth-last-child(n) can accept the same options as above (even, odd, formula); it just performs them in reverse order. Take the formula option we used before, nth-child(3n-1). If we were to write nth-last-child(3n-1), the CSS application would begin with the p tag before Bob, then continue to every three siblings in reverse order. Affected names would be Toby, Andy, Pam, and so on. In addition to selecting specific p tags based on which child they are, you can also select them in relation to other elements using nth-of-type(n).


nth-of-type(n)

This child selector will select child elements based on type. Consider we have two div tags, each containing eight character names. We want to give the first names in both div tags by giving them a larger font. We can write something like the code below.

p:nth-of-type(1){
font-size: 50px;
}

This would make Kelly and Pam larger than the rest of the names. Say you wanted to do the reverse and show the worst out of each group as larger text; you can use nth-last-of-type(n). It works the same as the nth-last-child(n) selector by starting from the end of each group in each div.


Application

One use case for nth-child is when you want to emphasize the difference in successive rows in a table. See this example on W3 Schools.

Another use case can be to highlight a range. Say you’re rendering a list of gamers and their high scores for a video game to show, say, MADMAX and DUSTIN are in the top five for Dig Dug.

If only they had nth-child selectors in the ’80s.

We can apply a combined nth-child and a negative range to make sure everyone can see the top four more prominently than the rest.

p:nth-child(n):nth-child(-n+4){
animation: pulsate 0.5s ease-in-out;
}
@keyframes pulsate{
0% {
transform: scale(1);
} 50% {
transform: scale(1.1);
} 100% {
transform: scale(1);
}
}

The above would look something like this.

If you ain’t first, you’re last.

nth-child is also useful for timed CSS animations using an animation-delay. See the below code, which uses a mixin-loop in LESS.

@iterations: 15;

.mixin-loop (@i) when (@i > 0) {
&:nth-child(@{i}) {
animation-delay: @i * 0.2s;
}
.mixin-loop(@i - 1);
}
p{
animation: ScaleIn 0.5s linear;
animation-fill-mode: both;
transform-origin: bottom left;
.mixin-loop(@iterations);
}

Below is what the animation would look like without the animation delay.

Yawn.

And here is what it would look like with the delay.

You can almost hear the timeless lyrics.

For more nth-child use cases, check out these CSS tricks.


Better Programming

Advice for programmers.

Matthew Croak

Written by

UI Engineer at Analytic Partners || Dog Lover

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade