Useful :nth-child Recipes

Avatar of Chris Coyier
Chris Coyier on (Updated on )

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

I get a little giddy when I come across perfect uses for :nth-child or :nth-of-type (read about the difference). The better you understand them, the more css nerdgasms you get to have!

In these simple “recipes” (really: expressions) I’ll arbitrarily use a flat list of list items and randomly chosen numbers. But it should be fairly obvious how to alter them to get similar selections.

Select Only the Fifth Element

li:nth-child(5) {
    color: green;   
}

To select the first element, you can use :first-child, or I bet you can guess how to alter the above to do it as well.

Select All But The First Five

li:nth-child(n+6) {
    color: green;   
}

If there were more than 10 elements here, it would select all of them beyond 5.

Select Only The First Five

li:nth-child(-n+5) {
    color: green;   
}

Select Every Fourth, Starting At The First

li:nth-child(4n-7) {  /* or 4n+1 */
    color: green;   
}

Select Only Odd or Even

li:nth-child(odd) {
    color: green;   
}
li:nth-child(even) {
    color: green;   
}

Select The Last Element

li:last-child {
    color: green;
}

Selects the 10th because we have 10 elements here, but if there was 8 it would select the 8th, or if there were 1,290 it would select the 1,290th.

Select the Second to Last Element

li:nth-last-child(2) {
    color: green;
}

Selects the 9th because we have 10 elements here, but if there were 30 elements it would select the 29th.

Wanna play?

Try the tester.

Browser Support

Interestingly enough, :first-child was supported by IE 7, but it’s not until IE 9 where the rest of this stuff is supported. Other than IE there isn’t much browser support concern, and if you are worried about IE, then use Selectivizr. If browser support stuff is interesting or important for you, definitely check out When can I use… which tracks this stuff very well.