The CSS :first-child selector
The CSS :first-child pseudo-class selects an element that is the first child of its parent — li:first-child matches the first list item. A common use is removing the top margin or border from the first item in a group. It only matches if the element really is the very first child.
Overview
:first-child matches an element when it is the first child of its parent. p:first-child selects a paragraph only when it is the opening element inside its container — nothing before it.
Its bread-and-butter use is tidying the edges of a list or stack. If every item has a top border or margin, the first one usually should not, and .item:first-child { border-top: 0; } removes it cleanly without special-casing the markup. It pairs naturally with :last-child for the other end.
One subtlety, the same as with :nth-child(): it checks position among all siblings. p:first-child means "a paragraph that is also the first child" — if the first child happens to be a heading, the rule matches nothing. When you want the first element of a particular type regardless of what comes before, use :first-of-type.
Syntax
/* no top border on the first item */
.item:first-child {
border-top: 0;
}
Example
<style>
.stack div { border-top: 2px solid #1c7ce9; padding: 10px 0; font: 15px system-ui, sans-serif; }
.stack div:first-child { border-top: 0; }
</style>
<div class="stack">
<div>First (no top border)</div>
<div>Second</div>
<div>Third</div>
</div>
Best practices
- Use it to strip the leading margin or border from the first item in a group.
- Pair it with :last-child to clean up both ends of a list or stack.
- Remember it checks position among all siblings — use
:first-of-typeto ignore other element types. - Modern layouts often avoid the need for it by using gap instead of per-item margins.
Frequently asked questions
What does :first-child do in CSS?
li:first-child matches the first list item.How do I remove the margin from the first item?
.item:first-child { margin-top: 0; } to clear the leading margin without changing the markup.Why is :first-child not matching my element?
:first-of-type to match the first of that element type.What is the difference between :first-child and :first-of-type?
:first-child matches only if the element is the very first child; :first-of-type matches the first element of its type, whatever precedes it.