CSS :nth-child() Pseudo-Class Selector

Published:
May 18, 2023
November 9, 2023
Updated:
November 9, 2023

What is the CSS :nth-child() selector?

:nth-child() is a CSS pseudo-class that selects elements based on their position in a collection of sibling elements. The selected positions are determined by an integer, keyword, or expression located inside the pseudo-class' parentheses.


/* nth-child with an integer */
:nth-child(1) { }

/* nth-child with a keyword */
:nth-child(even) { }

/* nth-child with an expression */
:nth-child(-4n + 1)

CSS :nth-child() Syntax

As a pseudo-class, nth-child is preceded by a colon and followed by a set of parentheses. Inside the parentheses we specify an argument, this argument represents which sibling child(ren) we want to select.

Syntax Breakdown

  • Before the colon we can write a selector for the element(s) that the nth-child must match.
  • Inside the parentheses (argument) we write which sibling child(ren) we want to select
    - We do this with an integer, an expression, or a keyword


/* Number - Selects the second list item */
li:nth-child(2) { }

/* Keyword - Selects even list items */
li:nth-child(even) { }

/* Expression - Selects every second list item, starting with the first */
li:nth-child(2n + 1)

Integer

When you're only specifying an integer, you're selecting a single element per group.

Integer Example

If you want to select the third list item, you can do so by simply inputting a 3 inside the nth-child's parentheses.

HTML


<ul>
  <li>List Item 1</li>
  <li>List Item 2</li>
  <li>List Item 3</li>
  <li>List Item 4</li>
</ul>

CSS


/* Select the third list item */
li:nth-child(3) {
	color: red;
}

Output

Integer Example 2

List items are naturally grouped together inside ordered, or unordered lists. When we specify that we want the second list-item selected, it selects the second list item in both lists.

HTML


<ul>
  <li>List Item 1</li>
  <li>List Item 2</li>
  <li>List Item 3</li>
  <li>List Item 4</li>
</ul>

<ul>
  <li>List Item 1</li>
  <li>List Item 2</li>
  <li>List Item 3</li>
  <li>List Item 4</li>
</ul>

CSS


/* Select the second list item */
li:nth-child(2) {
	color: red;
}

Output

Keywords

The keywords even and odd can be specified as our nth-child's argument. The even keyword selects the sibling child(ren) that are in even positions in their group (2nd, 4th, 6th, etc.). The odd keyword selects the sibling child(ren) that are in odd positions in their group (1st, 3rd, 5th, etc.).

Keywords Example 1

In this example, we have a single ordered list <ol> and we'd like to change all the even list items (2, 4, 6, etc.) to have red text. We can simply use the keyword even inside out nth-child's parentheses

HTML


<ol>
  <li>List Item</li>
  <li>List Item</li>
  <li>List Item</li>
  <li>List Item</li>
</ol>

CSS


/* Selects the even list items */
li:nth-child(even) {
  color: red;
}

Output

Keywords Example 2

Like the first keywords example, we'd like to select all the even list item elements, but this time we have two ordered lists <ol>. As you can see, by using nth-child(even) it changes all the even (2, 4, 6, etc.) list items' text color to red.

HTML


<ol>
  <li>List Item</li>
  <li>List Item</li>
  <li>List Item</li>
  <li>List Item</li>
</ol>

<ol>
  <li>List Item</li>
  <li>List Item</li>
  <li>List Item</li>
  <li>List Item</li>
</ol>

CSS


/* Selects the even list items */
li:nth-child(even) {
  color: red;
}

Output

Expression

As an alternative to using an integer, or a keyword, we can use the expression an or an + b. Using an expression allows us to make more advanced selections.

To breakdown the expression an + b:

  • a is an integer
  • n starts at 0 and iterates up by 1
  • + is an optional operator (you can use the - operator)
  • b is an optional integer that accompanies the optional operator
Expression Example 1

In this example, we're using the expression an - specifically 2n. This selects every second paragraph inside our "paragraphs" div.

HTML


<div class="paragraphs">
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <p>Paragraph 3</p>
  <p>Paragraph 4</p>
  <p>Paragraph 5</p>
</div>

CSS


.paragraphs p:nth-child(2n) {
  color: red;
}

Expression Explanation


# With the expression 2n

(2 x 0) = 0 
> No Match

(2 x 1) = 2
> Matches the 2nd Element (Paragraph 2)

(2 x 2) = 4
> Matches the 4th Element (Paragraph 4)

(2 x 3) = 6
> Matches the 6th Element

> etc.

Output

Expression Example 2

In this example, we're using the expression an + b - specifically 2n + 1. This selects every second paragraph inside our "paragraphs" div, starting with the first paragraph.

HTML


<div class="paragraphs">
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <p>Paragraph 3</p>
  <p>Paragraph 4</p>
  <p>Paragraph 5</p>
</div>

CSS


.paragraphs p:nth-child(2n + 1) {
  color: red;
}

Expression Explanation


# With the expression 2n + 1

(2 x 0) + 1 = 1
> Matches the 1st Element (Paragraph 1)

(2 x 1) + 1 = 3
> Matches the 3rd Element (Paragraph 3)

(2 x 2) + 1 = 5
> Matches the 5th Element (Paragraph 5)

Output

Expressions Example 3

In this example we're using the expression an + b again, but we're using a negative n value, specifically -n + 3.

HTML


<div class="paragraphs">
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <p>Paragraph 3</p>
  <p>Paragraph 4</p>
  <p>Paragraph 5</p>
</div>

CSS


.paragraphs p:nth-child(-n + 3) {
  color: red;
}

Expression Explanation


# With the expression -n + 3

(-1 x 0) + 3 = 3
> Matches the 3rd Element (Paragraph 3)

(-1 x 1) + 3 = 2
> Matches the 2nd Element (Paragraph 2)

(-1 x 2) + 3 = 
> Matches the 1st Element (Paragraph 1)

Output

Video Tutorial

Also available on YouTube and Instagram.

CSS :nth-child() Examples

The following examples are aimed to help you see how nth-child can be used in real-world scenarios.

Example 1 - Style Navbar Elements Differently

Example 1 Scenario

Your garden center website sells some items online and some items in-store. You'd like to host a sales event where all the items that you can purchase online are discounted, as long as they are not already on clearance pricing. The sidebar on the store lists links to all the different categories of products. The first three links are always clearance pricing, the rest of the links are never clearance pricing, but some of them are for in-store only. You'd like to highlight the fact that there is a sale on particular items by changing the appropriate links' text color to red.

Thinking This Through

  • We never want to select the first three list items
  • After the first three items only some of them should be selected based on if they're leading to products sold online
  • There may be other lists present in the product page for descriptions and other things, so we need to ensure our selection mechanism only selects the list in the sidebar
  • We'll use the class ecomm to identify list items that can be purchased online

Example 1 Solution

HTML


<!-- For the sake of example, our list items will represent links, normally we would also use anchor <a> tags -->
<div class="sidebar">
  <ul class="menu">
    <li class="ecomm">Deals on Topsoil</li>
    <li class="ecomm">Sales of the Week</li>
    <li class="ecomm">Deep Discounts!</li>
    <li class="ecomm">Flower Pots</li>
    <li>Build-It-Yourself Sheds</li>
    <li class="ecomm">Topsoil Bags</li>
    <li>Topsoil (Bulk)</li>
  </ul>
</div>

CSS


ul.menu li.ecomm:nth-child(n + 4) {
  color: red;
}

Expression Explanation


# With the expression n + 4

0 + 4 = 4
> Matches the 4th Element

1 + 4 = 5
> Matches the 5th Element

2 + 4 = 6
> Matches the 6th Element

3 + 4 = 7
> Matches the 7th Element


Using the calculations above, it shows that our expression (n + 4) is indeed skipping the first three elements - avoiding the items that have clearance pricing. But it also appears that it will start selecting all the items past the first three, even ones that are only sold in-store.

This is where the rest of the selector comes in...


Our selector is: **ul.menu li.ecomm:nth-child(n + 4)**

Breaking down the selector we have:
1. `ul.menu` that selects unordered list elements with the _menu_ class
2. `li.ecomm` selects list items with the class _ecomm_
3. Together these two form `ul.menu li.ecomm` which will select list items with the _ecomm_ class as long as they're contained within an unordered list with the _menu_ class.
4. Finally we add our nth-child to the selector `:nth-child(n + 4)` all together making it `ul.menu li.ecomm:nth-child(n + 4)` this selector... 
* selects list items with the _ecomm_ class 
* as long as they're inside an unordered list with the _menu_ class
* the first three list items will be skipped

Output

See the Pen :nth-child Example 1 by Matt Lawrence (@mattlawrence) on CodePen.

Example 2 - Dynamic Festive Styles

Example 2 Scenario

Your client's website has a collection of 4 content boxes on the home page. Each content box contains a heading, a paragraph, and a button. During the holiday season, your client would like every other button to be changed to green, with the remainder changed to red.

Thinking This Through

  • We'll have a wrapper div that will contain all of the content boxes, the wrapper div will have the class content-boxes
  • To select every other content box we'll use two selectors and the keywords even and odd with our nth-child

Example 2 Solution

HTML


<div class="content-boxes">
  <div class="content-box">
    <h1>Heading</h1>
    <p>Paragraph</p>
    <button>Button</button>
  </div>

  <div class="content-box">
    <h1>Heading</h1>
    <p>Paragraph</p>
    <button>Button</button>
  </div>

  <div class="content-box">
    <h1>Heading</h1>
    <p>Paragraph</p>
    <button>Button</button>
  </div>
  
  <div class="content-box">
    <h1>Heading</h1>
    <p>Paragraph</p>
    <button>Button</button>
  </div>
</div>

CSS


/* For example purposes, only the CSS selectors with nth-child are shown here */
.content-boxes .content-box:nth-child(even) button {
  background-color: red;
}

.content-boxes .content-box:nth-child(odd) button {
  background-color: green;
}

Output

See the Pen :nth-child Example 2 by Matt Lawrence (@mattlawrence) on CodePen.

Selector Explanations


The first selector is: **.content-boxes .content-box:nth-child(even) button**

Breaking down the selector:
1. `.content-boxes` selects our wrapper div
2. Building on that `.content-boxes .content-box` we're selecting elements with the _content-box_ class, inside our wrapper div
3. By adding our nth-child to the selector `.content-boxes .content-box:nth-child(even)` we're selecting the even elements with the _content-box_ class as long as they're inside our wrapper div
4. Finally, to select our buttons our selector becomes `.content-boxes .content-box:nth-child(even) button` which selects button elements inside every other element (even ones) with the _content-box_ class as long as it's inside our wrapper div

The second selector is: **.content-boxes .content-box:nth-child(even) button**
This selector does the same thing as the first selector, but for the odd content boxes rather than the even ones.


10% Off Web Development Courses

Learn web development skills with interactive courses (free & paid) by Scrimba.

Using our link, get 10% off all Scrimba plans - click here!

Note: We receive a monetary kickback if you sign up using our link.

Sources

Written by...
Matt Lawrence

When I'm not tinkering with websites and servers, I'm gaming it up....or writing something

More to Read...