Use promo code s-welcome to save 30% for the first month of your maintenance.

Get Started

How to use :nth-child selector in CSS

How to use :nth-child selector in CSS

The :nth-child selector in CSS is a powerful tool for targeting specific elements based on their position within a parent container. To use it, you specify a formula inside the parentheses, such as :nth-child(an+b), where “n” represents the position of the child element. For instance, :nth-child(2n) will target every even-numbered child.

To provide more flexibility, you can adjust the formula to target elements starting from a specific position or with a specific pattern. For example, :nth-child(3n+1) will select every third child, starting from the first one. This selector is particularly useful for styling or applying different rules to specific elements in a consistent manner, offering a dynamic approach to web design. Remember to experiment with different formulas to precisely target the elements you want in your CSS styles.

Below you can see a couple of examples on how to use :nth-child selector

:first-child

1
2
3
4
5
6
7
8
9
10

:last-child

1
2
3
4
5
6
7
8
9
10

:nth-child(2)

1
2
3
4
5
6
7
8
9
10

:nth-last-child(2)

1
2
3
4
5
6
7
8
9
10

:nth-child(odd)

1
2
3
4
5
6
7
8
9
10

:nth-child(even)

1
2
3
4
5
6
7
8
9
10

:nth-child(n +3)

1
2
3
4
5
6
7
8
9
10

:nth-child(3n + 3)

1
2
3
4
5
6
7
8
9
10

:nth-child(4n +2)

1
2
3
4
5
6
7
8
9
10

:not(:last-child)

1
2
3
4
5
6
7
8
9
10

Try it yourself

Experiment with different creative values for :nth-child in the editor below to observe the results.

1
2
3
4
5
6
7
8
9
10

Looking to improve existing or build a new website?

Let's work together