#Introduction
The :nth-child()
selector allows you to target specific elements within a parent, making styling and layouts more dynamic. Here's a quick breakdown:
- ->
:first-child
- Highlights the first element inside its parent. - ->
:last-child
- Targets the last element within the parent container. - ->
:nth-child(2)
- Selects the second element. - ->
:nth-child(3n)
- Applies styles to every third element (3, 6, 9, ...). - ->
:nth-child(odd)
- Selects odd-positioned elements (1st, 3rd, 5th, ...). - ->
:nth-child(even)
- Targets even-positioned elements (2nd, 4th, 6th, ...). - ->
:nth-child(n+4)
- Selects all elements from the 4th position onward. - ->
:nth-child(3n-1)
- Applies styles to positions one less than multiples of 3 (2, 5, 8, ...). - ->
:nth-child(-n+3)
- Selects the first three elements. - ->
: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!