CSS :last-of-type
Pseudo-Class
The :last-of-type
pseudo-class selects the last element of a specific type within its parent. It’s useful for styling the last occurrence of a particular tag inside a container.
1. Syntax
✅ This targets the last matching element of its type inside a parent, ignoring other elements.
2. Example – Styling the Last <p>
in a Section
✅ Only "Paragraph 3" turns red and bold, because it's the last <p>
inside <section>
.
3. Difference Between :last-of-type
and :last-child
Selector | Behavior |
---|---|
:last-of-type | Targets the last element of a specific type within a parent |
:last-child | Targets the last element of any type inside a parent |
Example
✅ Only the last <p>
(Second paragraph) turns blue because it is the last of its type.
✅ The <span>
would turn green if p:last-child
was applied because it's the last child.
4. Using :last-of-type
in Lists
✅ Only the last <li>
inside each parent will be italic.
5. Combining :last-of-type
with Other Selectors
Style Last <h2>
in Each Section
✅ The last <h2>
inside each <section>
gets underlined.
Style Last Button in a Form
✅ The last <button>
inside a <form>
gets a green background.
6. Browser Support
✅ Fully supported in all modern browsers (Chrome, Edge, Firefox, Safari, Opera).
7. Best Practices
✔ Use :last-of-type
when you need to target the last specific element in a parent.
✔ If the last element can be any type, use :last-child
instead.
✔ Combine with :nth-last-of-type()
for more advanced selections.