0
0
CssHow-ToBeginner · 3 min read

How to Use :last-of-type in CSS for Targeting Elements

Use the :last-of-type CSS pseudo-class to select the last element of a specific type among its siblings. For example, p:last-of-type targets the last <p> element inside its parent container.
📐

Syntax

The :last-of-type selector matches the last sibling element of its type (tag name) within its parent. It does not consider classes or IDs, only the element type.

  • element:last-of-type — selects the last element among siblings.
  • :last-of-type can be combined with other selectors for more specific targeting.
css
selector:last-of-type {
  /* CSS rules here */
}
💻

Example

This example shows how to style the last paragraph inside a container differently using :last-of-type. Only the last <p> gets the red text color.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>last-of-type Example</title>
<style>
  p:last-of-type {
    color: red;
    font-weight: bold;
  }
</style>
</head>
<body>
  <div>
    <p>First paragraph.</p>
    <p>Second paragraph.</p>
    <p>Last paragraph (styled red).</p>
  </div>
</body>
</html>
Output
A webpage with three paragraphs inside a container. The first two paragraphs have normal black text. The last paragraph text is bold and red.
⚠️

Common Pitfalls

Common mistakes when using :last-of-type include:

  • Expecting it to select the last child regardless of type — it only selects the last element of the specified type.
  • Confusing :last-of-type with :last-child. The latter selects the very last child element regardless of type.
  • Using it with classes or IDs incorrectly — it only works based on element type (tag name).
css
/* Wrong: selects last child, not last paragraph */
div p:last-child {
  color: blue;
}

/* Correct: selects last paragraph inside div */
div p:last-of-type {
  color: red;
}
📊

Quick Reference

SelectorDescription
element:last-of-typeSelects the last sibling of that element type
:last-of-typeSelects the last sibling of its type without specifying element
element:last-childSelects the last child regardless of type (different from last-of-type)

Key Takeaways

Use :last-of-type to target the last element of a specific type among siblings.
:last-of-type matches by element tag, not by class or ID.
Do not confuse :last-of-type with :last-child; they select different elements.
Combine :last-of-type with other selectors for precise styling.
It works well for styling the last paragraph, list item, or any repeated element.