CSS :first-of-type Pseudo Class

CSS :first-of-type Pseudo Class

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

selector:first-of-type { /* CSS styles here */ }

Example:

p:first-of-type { color: red; font-weight: bold; }

✅ The first <p> inside its parent will be red and bold.

2. Example – Styling the First Paragraph in a Section

<section> <p>This is the first paragraph in the section.</p> <p>This is another paragraph.</p> </section>
p:first-of-type { font-size: 1.5em; color: blue; }

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

<ul> <li>First item</li> <li>Second item</li> <li>Third item</li> </ul>
li:first-of-type { font-weight: bold; color: green; }

✅ The first <li> in the <ul> will be bold and green.

4. Difference Between :first-of-type and :first-child

SelectorSelects
:first-childOnly selects an element if it is the first child of its parent.
:first-of-typeSelects the first occurrence of a specific element type, even if it's not the first child.

Example:

<div> <span>Span 1</span> <p>Paragraph 1</p> <!-- Selected by `p:first-of-type` --> <p>Paragraph 2</p> </div>
p:first-of-type { color: red; }

✅ The first <p> is red, even though it’s not the first child.

5. Combining with Other Selectors

section p:first-of-type { background: yellow; }

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.

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