CSS :last-of-type

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

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

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

Where:

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

Examples

1. Styling the Last Paragraph

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

index.html

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

2. Styling the Last List Item of a Specific Type

Here, the last <li> element in an unordered list is styled with a bold font.

index.html

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

3. Styling the Last Heading of a Specific Type

The last <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:last-of-type {
            text-decoration: underline;
            color: green;
        }
    </style>
</head>
<body>
    <div>
        <h2>First Heading 2.</h2>
        <h2>Last Heading 2.</h2>
    </div>
</body>
</html>

4. Styling the Last Table Row

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

index.html

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

5. Styling the Last Image in a Container

The last <img> in a container is styled with a yellow border.

index.html

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