CSS :nth-child()
Pseudo-Class
The :nth-child(n)
pseudo-class selects an element based on its position among all children, counting from the beginning.
1. Syntax
✅ It allows you to target elements based on their order in the parent.
2. Example – Styling the 3rd Child
✅ The third <li>
(Item 3) will be red and bold.
3. Using Formulas (an + b
)
You can use numeric patterns with :nth-child()
:
Formula | Effect |
---|---|
:nth-child(1) | Selects the first child |
:nth-child(2) | Selects the second child |
:nth-child(odd) | Selects all odd-numbered children |
:nth-child(even) | Selects all even-numbered children |
:nth-child(3n + 1) | Selects every third child, starting with the first |
Example – Styling Every Third Item
✅ Every third <li>
gets a light blue background.
4. Example – Styling Table Rows
✅ Every odd-numbered row gets a yellow background.
5. :nth-child()
vs. :nth-of-type()
Pseudo-Class | Applies To | Condition |
---|---|---|
:nth-child(n) | Any element | Selects the n -th child (of any type) inside its parent. |
:nth-of-type(n) | Any element | Selects the n -th of its type inside its parent. |
Example
✅ p:nth-of-type(2)
→ Selects Paragraph 2 (second <p>
in the parent).
❌ p:nth-child(2)
→ Does nothing because the second child is <span>
.
6. Browser Support
✅ Fully supported in Chrome, Edge, Firefox, Safari, and Opera.
7. Best Practices
✔ Use :nth-child(n)
for styling elements based on order.
✔ Great for tables, lists, and dynamic content.
✔ Use :nth-of-type(n)
if selecting elements of a specific type.