CSS :first-child Pseudo Class

CSS :first-child Pseudo Class

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

selector:first-child { /* CSS styles here */ }

Example:

p:first-child { font-weight: bold; color: blue; }

✅ This styles only the first <p> inside its parent.

2. Example – Styling the First List Item

<ul> <li>First Item</li> <li>Second Item</li> <li>Third Item</li> </ul>
li:first-child { color: red; font-weight: bold; }

✅ The first <li> will be red and bold.
✅ Other <li> elements remain unchanged.

3. Example – Styling the First Paragraph in a Div

<div> <p>First paragraph</p> <p>Second paragraph</p> </div>
p:first-child { font-size: 20px; color: green; }

✅ 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

<div> <h2>Heading</h2> <p>First paragraph</p> <p>Second paragraph</p> </div>
p:first-child { color: blue; }

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-ClassWhat it Selects
:first-childThe very first child of any type inside its parent
:first-of-typeThe first element of a specific type inside its parent

Example:

p:first-of-type { color: red; }

✅ 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.

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