Episode 21 of 53

First and Last of Type Selector

Learn :first-of-type and :last-of-type for targeting the first/last element of a specific type.

While :first-child matches the first child regardless of type, :first-of-type matches the first child of a specific element type.

The Difference

<div>
    <h2>Title</h2>
    <p>First paragraph</p>
    <p>Second paragraph</p>
</div>
/* Does NOT match — the <p> is not the first child (h2 is) */
p:first-child { color: red; }

/* DOES match — it IS the first <p> among its siblings */
p:first-of-type { color: blue; }

:last-of-type

/* Target the last paragraph in a section */
section p:last-of-type {
    margin-bottom: 0;
    font-style: italic;
}

Practical Uses

  • Styling the first paragraph of an article as an intro
  • Removing margins from the last element of a type
  • Adding decorative styles to specific positions
article p:first-of-type {
    font-size: 1.25rem;
    color: #555;
    line-height: 1.8;
}

article p:last-of-type {
    border-bottom: 2px solid #eee;
    padding-bottom: 1rem;
}