CSS :last-child Pseudo Class

CSS :last-child Pseudo Class

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

selector:last-child { /* Styles for the last child */ }

Targets the last child of its parent, regardless of its tag type.

2. Example – Styling the Last Child in a div

<div> <p>First paragraph</p> <p>Second paragraph</p> <span>Last child</span> </div>
span:last-child { color: red; font-weight: bold; }

Only <span> turns red and bold because it’s the last child inside <div>.

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

SelectorBehavior
:last-childTargets the last child of a parent, regardless of type
:last-of-typeTargets the last element of a specific type

Example

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

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

li:last-child { font-style: italic; }

Only the last <li> in each <ul> or <ol> is italic.

5. Combining :last-child with Other Selectors

Style Last Button in a Form

form button:last-child { background-color: green; }

Only the last <button> inside <form> gets a green background.

Style Last Paragraph in an Article

article p:last-child { text-decoration: underline; }

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.

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