CSS :first-of-type
Pseudo-Class
The :first-of-type
pseudo-class selects the first element of a specified type among its siblings inside a parent element. It is useful when styling the first occurrence of a particular HTML tag within a container.
1. Syntax
Example:
✅ The first <p>
inside its parent will be red and bold.
2. Example – Styling the First Paragraph in a Section
✅ The first <p>
inside <section>
will be blue and larger, but others will remain unchanged.
3. Example – Styling the First List Item in a <ul>
✅ The first <li>
in the <ul>
will be bold and green.
4. Difference Between :first-of-type
and :first-child
Selector | Selects |
---|---|
:first-child | Only selects an element if it is the first child of its parent. |
:first-of-type | Selects the first occurrence of a specific element type, even if it's not the first child. |
Example:
✅ The first <p>
is red, even though it’s not the first child.
5. Combining with Other Selectors
✅ The first <p>
in each <section>
gets a yellow background.
6. Browser Support
✅ Fully supported in Chrome, Edge, Firefox, Safari, and Opera.
7. Best Practices
✔ Use :first-of-type
when you want to target the first occurrence of a tag inside a parent.
✔ Don’t confuse :first-of-type
with :first-child
, as :first-of-type
is more flexible.
✔ Combine it with other selectors for precise targeting.