:nth-child & Pattern Matching Selectors
The :nth-child() pseudo-class selects elements based on their position using formulas. Master the An+B formula for advanced patterns like every 3rd element, first 5 elements, or custom repeating patterns.
:nth-child Formulas
- :nth-child(3) — Select the 3rd child exactly
- :nth-child(odd) / :nth-child(even) — Alternate selection. Equivalent to :nth-child(2n+1) and :nth-child(2n)
- :nth-child(3n) — Every 3rd element: 3, 6, 9, 12...
- :nth-child(3n+1) — Every 3rd starting from 1st: 1, 4, 7, 10...
- :nth-child(-n+5) — First 5 elements only
- :nth-last-child(n) — Count from the end instead of the beginning
- :nth-of-type(n) — Like nth-child but only counts elements of the same type (ignores other siblings)
Pattern Code
/* Zebra stripes */
tr:nth-child(even) { background: #f8f9fa; }
/* Every 3rd card has accent color */
.card:nth-child(3n) { border-left: 4px solid #E44D26; }
/* First 3 items are featured */
.item:nth-child(-n+3) { font-size: 1.2em; font-weight: bold; }
/* Last 2 items */
.item:nth-last-child(-n+2) { opacity: 0.7; }
/* Grid pattern: 3 columns with different spans */
.grid-item:nth-child(4n+1) { grid-column: span 2; }
/* Masonry-like pattern */
.gallery img:nth-child(3n+1) { grid-row: span 2; }
.gallery img:nth-child(5n+3) { grid-column: span 2; }Tip
:nth-child(-n+X) selects the first X elements. Use it for 'featured' items: .post:nth-child(-n+3) styles the first 3 posts differently. Combine with :nth-last-child(-n+2) for the last 2 items.
Selectors target HTML elements for styling
Common Mistake
Confusing :nth-child with :nth-of-type. :nth-child(2) selects the 2nd CHILD regardless of type. :nth-of-type(2) selects the 2nd element OF THAT TYPE. In a mixed container, they produce different results.
Practice Task
Style a table and card grid: (1) Zebra-stripe rows with :nth-child(even), (2) Feature first 3 cards with :nth-child(-n+3), (3) Accent every 3rd card with :nth-child(3n), (4) Fade last 2 with :nth-last-child(-n+2).
Quick Quiz
Key Takeaways
- The :nth-child() pseudo-class selects elements based on their position using formulas.
- :nth-child(3) — Select the 3rd child exactly
- :nth-child(odd) / :nth-child(even) — Alternate selection. Equivalent to :nth-child(2n+1) and :nth-child(2n)
- :nth-child(3n) — Every 3rd element: 3, 6, 9, 12...