CSS :last-child
Pseudo-Class
The :last-child
pseudo-class selects the last child of a parent, regardless of its type. It’s useful for styling the final element inside a container.
1. Syntax
✅ Targets the last child of its parent, regardless of its tag type.
2. Example – Styling the Last Child in a div
✅ Only <span>
turns red and bold because it’s the last child inside <div>
.
3. Difference Between :last-child
and :last-of-type
Selector | Behavior |
---|---|
:last-child | Targets the last child of a parent, regardless of type |
:last-of-type | Targets the last element of a specific type |
Example
✅ Nothing happens to <p>
with :last-child
because it's not the last child.
✅ The last <p>
turns green because :last-of-type
selects the last <p>
inside <div>
.
4. Using :last-child
in Lists
✅ Only the last <li>
in each <ul>
or <ol>
is italic.
5. Combining :last-child
with Other Selectors
Style Last Button in a Form
✅ Only the last <button>
inside <form>
gets a green background.
Style Last Paragraph in an Article
✅ Only the last <p>
in an <article>
is underlined.
6. Browser Support
✅ Fully supported in all modern browsers (Chrome, Edge, Firefox, Safari, Opera, etc.).
7. Best Practices
✔ Use :last-child
when you want to target the very last element inside a parent.
✔ If you need to style the last specific type, use :last-of-type
.
✔ Combine with :nth-last-child(n)
for advanced selections.