Structural Pseudo-Classes: :nth-child and :nth-of-type
What you'll learn: How to select elements using powerful formulas that target specific positions or create repeating patterns.
The Core Idea
While :first-child and :last-child let you select the first or last element, :nth-child() and :nth-of-type() unlock pattern-based selection. You can target every third item, all odd rows, the 5th paragraph, or complex repeating patterns using simple formulas.
Think of it like this: Imagine you're organizing books on shelves and want to mark every third book with a ribbon, or only books at positions 2, 4, 6, 8... These pseudo-classes let you create those rules automatically.
How They Work
Both pseudo-classes accept arguments in parentheses:
Simple numbers:
:nth-child(3)— selects the 3rd child:nth-of-type(2)— selects the 2nd element of its type
Keywords:
:nth-child(odd)— selects 1st, 3rd, 5th children...:nth-child(even)— selects 2nd, 4th, 6th children...
Formulas (an + b):
:nth-child(3n)— every 3rd element (3, 6, 9, 12...):nth-child(3n+1)— pattern starting at 1 (1, 4, 7, 10...):nth-child(2n+3)— every other, starting at 3 (3, 5, 7, 9...)
The Difference
:nth-child() counts all sibling elements, while :nth-of-type() counts only elements of the same type. For example, p:nth-of-type(2) targets the second <p> element among its siblings, ignoring any <div> or other elements in between.
Key Takeaway: :nth-child() and :nth-of-type() use formulas like (an + b) to select elements at specific positions or in repeating patterns, giving you precise control over which elements receive styling.