Menu
Coddy logo textTech

Pattern Power: Using nth-child

Part of the CSS Mastery section of Coddy's HTML journey — lesson 15 of 43.

The :nth-child() pseudo-class selects elements based on their order inside a parent, using a number or a pattern to choose which ones.

For example, we have a list:

<ul>
  <li>First item</li>
  <li>Second item</li>
  <li>Third item</li>
  <li>Fourth item</li>
  <li>Fifth item</li>
</ul>

This is how we select even-numbered list items:

li:nth-child(even) {
  background-color: lightblue;
}

This is how we select the 3rd item:

li:nth-child(3) {
  font-weight: bold;
}

 This is how we select every 5th item:

li:nth-child(5n) {
  color: red;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Create a CSS rule using :nth-child() to give every third <div> a yellow background.

Cheat sheet

The :nth-child() pseudo-class selects elements based on their order inside a parent.

Select even-numbered elements:

li:nth-child(even) {
  background-color: lightblue;
}

Select a specific element (3rd):

li:nth-child(3) {
  font-weight: bold;
}

Select every nth element (every 5th):

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

Try it yourself

<!DOCTYPE html>
<html>
<head>
    <title>Pattern Power: Using nth-child</title>
  <style>
    /* Write your CSS rule here */
    
  </style>
</head>
<body>
  <div class="container">
    <div>Item 1</div>
    <div>Item 2</div>
    <div>Item 3</div>
    <div>Item 4</div>
    <div>Item 5</div>
    <div>Item 6</div>
    <div>Item 7</div>
    <div>Item 8</div>
    <div>Item 9</div>
    <div>Item 10</div>
  </div>
</body>
</html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in CSS Mastery