CSS :last-of-type Pseudo Class

CSS :last-of-type Pseudo Class

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

selector:last-of-type { /* Styles for the last element of the specified type */ }

✅ This targets the last matching element of its type inside a parent, ignoring other elements.

2. Example – Styling the Last <p> in a Section

<section> <p>Paragraph 1</p> <p>Paragraph 2</p> <span>Not a paragraph</span> <p>Paragraph 3 (Last of Type)</p> </section>
p:last-of-type { color: red; font-weight: bold; }

Only "Paragraph 3" turns red and bold, because it's the last <p> inside <section>.

3. Difference Between :last-of-type and :last-child

SelectorBehavior
:last-of-typeTargets the last element of a specific type within a parent
:last-childTargets the last element of any type inside a parent

Example

<div> <p>First paragraph</p> <p>Second paragraph</p> <span>Some text</span> </div>
p:last-of-type { color: blue; } p:last-child { color: green; }

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

li:last-of-type { font-style: italic; }

Only the last <li> inside each parent will be italic.

5. Combining :last-of-type with Other Selectors

Style Last <h2> in Each Section

section h2:last-of-type { text-decoration: underline; }

✅ The last <h2> inside each <section> gets underlined.

Style Last Button in a Form

form button:last-of-type { background-color: green; }

✅ 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.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close