:last-child
Matches an element that is the last child of its parent.
Example
#.crumbs li:not(:last-child)::after {
content: "/";
margin: 0 8px;
color: #71717a;
}
.crumbs li:last-child {
color: #fff;
font-weight: 600;
}<ol class="crumbs" style="display: flex; flex-wrap: wrap; margin: 0; padding: 0; list-style: none; color: #a1a1aa;">
<li>Docs</li>
<li>CSS</li>
<li>:last-child</li>
</ol>Definition and usage
#The :last-child pseudo-class is the mirror image of :first-child: it selects the element standing at the very end of its parent. A typical example is removing the bottom margin of the last paragraph in a card, so the gap from the edge is the same on every side.
The same trap applies as with :first-child. The selector p:last-child only works when the paragraph is truly the last child. If a button or a footer follows it, nothing gets selected. That’s where :last-of-type helps.
The pseudo-class stays live. When a script appends a new element to the end of a list, the previous last element stops matching, and the style moves to the new element with no change to the CSS at all.
Syntax
#selector:last-child { property: value; }Example selectors
#- The last bullet of the list, because it closes out its parent.
- Nothing lights up: the article’s last child is the button.
- The last paragraph among paragraphs, even if another element follows it.
- Every bullet except the last, for example for separators inserted between elements.
Example selectors in practice
#li:last-child
li:last-child { background: #7c3aed; color: #fff; }p:last-child
p:last-child { background: #7c3aed; color: #fff; }p:last-of-type
p:last-of-type { background: #7c3aed; color: #fff; }li:not(:last-child)
li:not(:last-child) { background: #7c3aed; color: #fff; }Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- In cards and dialogs, zero out the bottom margin of the last child (
.card > :last-child { margin-bottom: 0 }). The gap from the bottom edge will match the top one. - The simplest way to add separators between elements is
li:not(:last-child)::after. The last element won’t get a stray character. - When different elements can appear at the end of the parent,
:last-of-typeis more resilient than:last-child.
Related entries
#- :first-childMatches an element that is the first child of its parent.
- :nth-child()Selects elements by position among siblings: every other one, every third, the first three, or everything from the seventh on.
- :nth-of-type()Selects elements by position among siblings with the same tag, for example every other image or the third paragraph.
- :not()Selects elements that match neither the given selector nor any selector in the list.
Spotted a mistake or missing an example? Write to us.