Definition and Usage
:last-child
pseudo-class selector
selects the element that is the last child of its parent.
The :last-child
pseudo-class selector is the same as :nth-last-child(1)
.
Additional Explanation
:nth-last-child(n)
is a pseudo-class that selects the element that is the n
th child of its parent, counting from the end.
Basic Example
<ol>
<li>li</li>
<li>li</li>
<li>li</li>
<li>li</li>
</ol>
li:last-child {
background-color: yellowgreen;
}
- li
- li
- li
- li
Syntax
:last-child {
/* ... */
}
Examples
These examples help you understand how the :last-child
pseudo-class selector works.
Styling the Last Paragraph Element
<article>
<h2>Heading Element</h2>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</article>
article p:last-child {
background-color: yellowgreen;
}
Heading Element
Paragraph 1
Paragraph 2
Styling Nested Elements
<article>
<div>This 'div' is the first one.</div>
<div>This <span>nested 'span' is both the first and the last one.</span>!</div>
<div>
This <em>nested 'em' is the first one.</em>, but this <em>nested 'em' is the last one.</em>!
</div>
<div>This <span>nested 'span' is styled. It is both the first and the last one.</span>!</div>
<p>This 'p' is not the last child.</p>
<div>This 'div' is the last one.</div>
</article>
article *:last-child {
background-color: yellowgreen;
}
This 'div' is the first one.
This nested 'span' is both the first and the last one.!
This nested 'em' is the first one., but this nested 'em' is the last one.!
This nested 'span' is styled. It is both the first and the last one.!
This 'p' is not the last one.
This 'div' is the last one.
Browser compatibility
Last updated: 2025-09-25
Selector |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
---|---|---|---|---|
:last-child
|
1 | 12 | 1 | 3.1 |
Matches elements with no parent | 57 | 79 | 52 | Not supported |
Specifications
Specification | |
---|---|
:last-child
|
Selectors Level 4 #the-last-child-pseudo |
References
See also
- CSS :first-child Pseudo-Class – Select the First Child Element
- CSS :nth-child() Pseudo-Class – Select the nth Child Element
- CSS :nth-last-child() Pseudo-Class – Select the nth Child Element from the End
- CSS :nth-of-type() Pseudo-Class – Select the nth Child of the Same Tag
- CSS :nth-last-of-type() Pseudo-Class – Select the nth Child from the End of the Same Tag
- CSS :first-of-type Pseudo-Class – Select the First Child of the Same Tag
- CSS :last-of-type Pseudo-Class – Select the Last Child of the Same Tag
- CSS :focus-within Pseudo-Class Selector
- CSS ::placeholder Pseudo-Element for Styling Placeholder Text