JT Book a call

Blog

How to use :nth-child in CSS

Published

1 min read

How to use :nth-child in CSS
In this post

The :nth-child pseudo-class allows to select one and more elements based on their source order.

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
</ul>

Let’s look at simple examples for how this can be do:

Select the first list item #

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

Also, you can use first-child pseudo-class for this

li:first-child {
  color: red;
}

Image description

Select the 5th list item #

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

Image description

Select every child elements whose index is odd #

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

Image description

Select every child elements whose index is even #

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

Image description

Select every 3rd list item starting with first #

li:nth-child(3n — 2) {
  color: red;
}

Image description

Select every 3rd list item starting with 2nd #

li:nth-child(3n — 1) {
  color: red;
}

Image description

Select every 3rd child item #

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

Image description

Select the first three items of the list #

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

Image description

Select the last element of the list #

li:last-child {
  color: red;
}

Image description

Read next

Tell us what you need built

JetThoughts has been building software since 2008. Book a call, or write to sales@jetthoughts.com. You'll leave the call with a written one-page scope within 2 working days.

#01 Paul Keen
Paul KeenChief Technology Officer & Open Source Contributor

A 30-minute call; pick a time.