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
:last-child
:nth-child(2)
:nth-last-child(2)
:nth-child(odd)
:nth-child(even)
:nth-child(n +3)
:nth-child(3n + 3)
:nth-child(4n +2)
:not(:last-child)
Try it yourself
Experiment with different creative values for :nth-child
in the editor below to observe the results.