Mastering :nth-child() in CSS

Under CSS Published at February 11, 2025 Updated at February 11, 2025

The :nth-child() selector allows you to target specific elements within a parent, making styling and layouts more dynamic. Here's a quick breakdown:

  1. ->:first-child - Highlights the first element inside its parent.
  2. ->:last-child - Targets the last element within the parent container.
  3. ->:nth-child(2) - Selects the second element.
  4. ->:nth-child(3n) - Applies styles to every third element (3, 6, 9, ...).
  5. ->:nth-child(odd) - Selects odd-positioned elements (1st, 3rd, 5th, ...).
  6. ->:nth-child(even) - Targets even-positioned elements (2nd, 4th, 6th, ...).
  7. ->:nth-child(n+4) - Selects all elements from the 4th position onward.
  8. ->:nth-child(3n-1) - Applies styles to positions one less than multiples of 3 (2, 5, 8, ...).
  9. ->:nth-child(-n+3) - Selects the first three elements.
  10. ->:nth-last-child(n) - Targets the nth element from the end of the parent container.

#Visualization

🎯 Hover/Click to Understand `:nth-child()` in CSS 🚀

:first-child
1
2
3
4
5
6
7
8
:last-child
1
2
3
4
5
6
7
8
:nth-child(2)
1
2
3
4
5
6
7
8
:nth-child(3n)
1
2
3
4
5
6
7
8
:nth-child(odd)
1
2
3
4
5
6
7
8
:nth-child(even)
1
2
3
4
5
6
7
8
:nth-child(n+4)
1
2
3
4
5
6
7
8
:nth-child(3n-1)
1
2
3
4
5
6
7
8
:nth-child(-n+3)
1
2
3
4
5
6
7
8
:nth-last-child(2)
1
2
3
4
5
6
7
8

💡 Use these to create dynamic UI effects, table row styling, or alternate list designs!

Last updated on

February 11, 2025

# of hits