Role of CSS :first-of-type Selector

The CSS :first-of-type pseudo-class selector targets the first element of its type among siblings within the same parent container. It's particularly useful for styling the first occurrence of specific HTML elements without adding extra classes.

Syntax

element:first-of-type {
    property: value;
}

Example: First Paragraph Styling

The following example demonstrates how to style the first paragraph element within its parent −

<!DOCTYPE html>
<html>
<head>
<style>
    p:first-of-type {
        background-color: orange;
        font-weight: bold;
        padding: 10px;
        margin-bottom: 10px;
    }
    
    p {
        margin: 5px 0;
        padding: 5px;
        border-left: 3px solid #ccc;
    }
</style>
</head>
<body>
    <div>
        <h2>Article Title</h2>
        <p>This is the first paragraph - it gets orange background.</p>
        <p>This is the second paragraph - normal styling.</p>
        <p>This is the third paragraph - also normal styling.</p>
    </div>
</body>
</html>
The first paragraph appears with an orange background and bold text, while the second and third paragraphs display with normal styling and a gray left border.

Example: Multiple Element Types

The :first-of-type selector works independently for each element type −

<!DOCTYPE html>
<html>
<head>
<style>
    h3:first-of-type {
        color: #e74c3c;
        text-decoration: underline;
    }
    
    p:first-of-type {
        background-color: #f39c12;
        padding: 8px;
    }
    
    li:first-of-type {
        font-weight: bold;
        color: #2ecc71;
    }
</style>
</head>
<body>
    <div>
        <h3>First Heading</h3>
        <p>First paragraph gets orange background.</p>
        <h3>Second Heading</h3>
        <p>Second paragraph has normal styling.</p>
        <ul>
            <li>First list item is bold and green</li>
            <li>Second list item is normal</li>
        </ul>
    </div>
</body>
</html>
The first h3 appears red and underlined, the first paragraph has an orange background, and the first list item displays in bold green text. Other elements of the same type appear with normal styling.

Conclusion

The :first-of-type selector provides an efficient way to target the first occurrence of any element type within its parent. It's more flexible than :first-child since it considers element types rather than position among all siblings.

Updated on: 2026-03-15T12:19:24+05:30

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements