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