CSS :nth-child() Pseudo Class

CSS :nth-child() Pseudo Class

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

selector:nth-child(n) { /* Styles for the nth child */ }

✅ It allows you to target elements based on their order in the parent.

2. Example – Styling the 3rd Child

<ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> </ul>
li:nth-child(3) { color: red; font-weight: bold; }

✅ The third <li> (Item 3) will be red and bold.

3. Using Formulas (an + b)

You can use numeric patterns with :nth-child():

FormulaEffect
: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

css
li:nth-child(3n) { background-color: lightblue; }

✅ Every third <li> gets a light blue background.

4. Example – Styling Table Rows

<table> <tr><td>Row 1</td></tr> <tr><td>Row 2</td></tr> <tr><td>Row 3</td></tr> <tr><td>Row 4</td></tr> <tr><td>Row 5</td></tr> </table>
tr:nth-child(odd) { background-color: yellow; }

Every odd-numbered row gets a yellow background.

5. :nth-child() vs. :nth-of-type()

Pseudo-ClassApplies ToCondition
:nth-child(n)Any elementSelects the n-th child (of any type) inside its parent.
:nth-of-type(n)Any elementSelects the n-th of its type inside its parent.

Example

<div> <p>Paragraph 1</p> <span>Span 1</span> <p>Paragraph 2</p> <span>Span 2</span> <p>Paragraph 3</p> </div>
p:nth-of-type(2) { color: red; } p:nth-child(2) { color: blue; }

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.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close