CSS :first-child and :last-child — Edge Element Selection
Learn CSS :first-child and :last-child pseudo-classes for targeting the first and last elements among siblings. Essential for removing borders, margins, and handling edge cases.
Detailed Explanation
CSS :first-child and :last-child
These pseudo-classes target elements based on their position as the first or last child of their parent element.
Syntax
li:first-child {
border-top: none;
}
li:last-child {
border-bottom: none;
}
How They Work
<ul>
<li>First</li> <!-- matches :first-child -->
<li>Middle</li>
<li>Last</li> <!-- matches :last-child -->
</ul>
For a single child element, both :first-child and :last-child match (and so does :only-child).
Common Patterns
Remove trailing separators:
.breadcrumb li:last-child::after {
content: none; /* no separator after last item */
}
Remove edge margins:
.grid > *:first-child { margin-top: 0; }
.grid > *:last-child { margin-bottom: 0; }
Special first-paragraph styling:
article > p:first-child {
font-size: 1.2rem;
font-weight: 500;
}
Related Pseudo-classes
| Selector | Matches |
|---|---|
:first-child |
First child of parent |
:last-child |
Last child of parent |
:first-of-type |
First of its tag type |
:last-of-type |
Last of its tag type |
:only-child |
Element with no siblings |
:only-of-type |
Only element of its tag type |
Specificity
Each pseudo-class adds (0, 1, 0) to specificity.
Use Case
The :first-child and :last-child pseudo-classes are essential for handling edge cases in lists, grids, and navigation. Developers use them to remove top/bottom borders, adjust margins and padding for the first/last item, add special styling to introductory paragraphs, handle separator characters in breadcrumbs, and create clean card layouts without doubled borders.