CSS :first-child and :last-child - Edge Element Styling
Style the first and last elements in a container with :first-child and :last-child. Learn specificity, common patterns for borders, margins, and list styling.
Detailed Explanation
:first-child and :last-child
These structural pseudo-classes select elements based on their position relative to their parent's first or last child.
Syntax
li:first-child {
border-top: none;
}
li:last-child {
border-bottom: none;
}
Common Patterns
Remove borders from edges:
.list-item {
border-bottom: 1px solid #eee;
}
.list-item:last-child {
border-bottom: none;
}
Remove margin from first/last:
.section:first-child {
margin-top: 0;
}
.section:last-child {
margin-bottom: 0;
}
Style first paragraph differently:
article p:first-child {
font-size: 1.2em;
font-weight: 500;
}
Important Gotcha
:first-child matches the element if it is the first child of its parent — not the first child of a specific type. If a <span> comes before a <p>, then p:first-child will NOT match:
<div>
<span>I'm first!</span>
<p>I am NOT p:first-child</p>
</div>
Use :first-of-type instead when you need the first element of a specific tag.
:only-child
An element that is both :first-child and :last-child can also be matched with :only-child:
.card:only-child {
max-width: 600px;
margin: 0 auto;
}
Specificity
Both have specificity (0, 1, 0) — the same as a class selector.
Use Case
First-child and last-child selectors are used constantly in component styling: removing borders from the first or last item in a list, adjusting margins at container edges, highlighting the first paragraph in an article, and handling single-child layouts. They help create clean visual spacing without needing extra classes on edge elements.