DEV Community

Cover image for How to use :nth-child in CSS
JetThoughts Dev for JetThoughts

Posted on • Edited on • Originally published at jetthoughts.com

How to use :nth-child in CSS

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>
Enter fullscreen mode Exit fullscreen mode

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

Select the first list item

li:nth-child(1) {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

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

li:first-child {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

Image description

Select the 5th list item

li:nth-child(5) {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

Image description

Select every child elements whose index is odd

li:nth-child(odd) {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

Image description

Select every child elements whose index is even

li:nth-child(even) {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

Image description

Select every 3rd list item starting with first

li:nth-child(3n β€” 2) {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

Image description

Select every 3rd list item starting with 2nd

li:nth-child(3n β€” 1) {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

Image description

Select every 3rd child item

li:nth-child(3n) {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

Image description

Select the first three items of the list

li:nth-child(-n+3) {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

Image description

Select the last element of the list

li:last-child {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (1)

Collapse
 
elayachiabdelmajid profile image
Abdelmajid E.

great toturial