CSS :first-child
Pseudo-Class
The :first-child
pseudo-class selects the first child element of its parent. It is useful for applying unique styles to the first element inside a container, such as paragraphs, list items, or table rows.
1. Syntax
Example:
✅ This styles only the first <p>
inside its parent.
2. Example – Styling the First List Item
✅ The first <li>
will be red and bold.
✅ Other <li>
elements remain unchanged.
3. Example – Styling the First Paragraph in a Div
✅ The first <p>
inside the <div>
gets a larger font and green color.
4. Important Notes on :first-child
🚨 Must be the first child of its parent
❌ This does not work because <p>
is not the first child (the <h2>
is).
✅ To target the first <p>
in any position, use :first-of-type
instead.
5. :first-child
vs :first-of-type
Pseudo-Class | What it Selects |
---|---|
:first-child | The very first child of any type inside its parent |
:first-of-type | The first element of a specific type inside its parent |
Example:
✅ Targets the first <p>
inside a parent, even if it’s not the first child.
6. Browser Support
✅ Fully supported in Chrome, Edge, Firefox, Safari, and Opera.
7. Best Practices
✔ Use :first-child
when styling only the first element inside a parent.
✔ Use :first-of-type
if you want the first element of a specific type.
✔ Be mindful of HTML structure, as :first-child
requires the element to be truly first.