CSS :first-of-type

The CSS :first-of-type pseudo-class applies styles to the first element of a specified type within its parent. This is useful for targeting and styling the first occurrence of an element type in a container, regardless of its position among other element types.

The syntax for the :first-of-type pseudo-class is:

</>
Copy
selector:first-of-type {
    property: value;
}

Where:

ParameterDescription
selectorThe element to which the :first-of-type pseudo-class will apply.
propertyThe CSS property to style the element.
valueThe value assigned to the CSS property.

Examples

1. Styling the First Paragraph

In this example, the first <p> element in a parent container is styled with blue text color.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        p:first-of-type {
            color: blue;
        }
    </style>
</head>
<body>
    <div>
        <p>First paragraph.</p>
        <p>Second paragraph.</p>
    </div>
</body>
</html>

2. Styling the First List Item of a Specific Type

Here, the first <li> element in an ordered list is styled with bold text.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        ol li:first-of-type {
            font-weight: bold;
        }
    </style>
</head>
<body>
    <ol>
        <li>First ordered list item.</li>
        <li>Second ordered list item.</li>
    </ol>
    <ul>
        <li>Unordered list item.</li>
    </ul>
</body>
</html>

3. Styling the First Heading of a Specific Type

The first <h2> element in a container is styled with a green underline.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        h2:first-of-type {
            text-decoration: underline;
            color: green;
        }
    </style>
</head>
<body>
    <div>
        <h2>First Heading 2.</h2>
        <h2>Second Heading 2.</h2>
        <h1>First Heading 1.</h1>
    </div>
</body>
</html>

4. Styling the First Table Row

In this example, the first <tr> of a table is styled with a yellow background.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        tr:first-of-type {
            background-color: yellow;
        }
    </style>
</head>
<body>
    <table border="1">
        <tr><td>Row 1</td></tr>
        <tr><td>Row 2</td></tr>
    </table>
</body>
</html>

5. Styling the First Image in a Container

The first <img> in a container is styled with a red border.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        img:first-of-type {
            border: 2px solid red;
        }
    </style>
</head>
<body>
    <div>
        <img src="/img/lion.jpg" alt="First Image" width="100">
        <img src="/img/dragonfly.jpg" alt="Second Image" width="100">
    </div>
</body>
</html>