nth-child Selectors
The :nth-child() pseudo-class provides powerful pattern-based selection.
Basic nth-child
Select elements by their position:
:nth-child(1)- first element:nth-child(3)- third element:nth-child(5)- fifth element
Even and Odd
Select alternating elements:
:nth-child(even)- 2nd, 4th, 6th...:nth-child(odd)- 1st, 3rd, 5th...
Zebra Striped Table
The Formula: an+b
:nth-child(an+b) selects elements at position an+b:
:nth-child(3n)- every 3rd (3, 6, 9...):nth-child(3n+1)- 1st of every 3 (1, 4, 7...):nth-child(2n+1)- same as odd
Select First N Elements
:nth-child(-n+3) selects the first 3 elements.
:nth-last-child
Count from the end:
:nth-last-child(1)- last element:nth-last-child(2)- second to last
Grid Pattern Styling
:nth-of-type
Like nth-child but only counts matching elements:
p:nth-of-type(2) selects the 2nd <p>, ignoring other elements.
Exercise: Stripe Table Rows
Add zebra stripes to odd table rows:
Up next · Lesson 13 of 27
Understanding Specificity
2 min read
12 of 27 lessons done

Ask Byte about this lesson
A private chat about this lesson. Byte has read the whole lesson, answers in seconds, and shows the section each answer comes from. Ask follow-ups in any language.
Questions & Answers
Public questions about this lesson. The AI Tutor answers right away in your language, the FreeAcademy team checks answers, and every learner can read them.

