😄 This post is based on the content from coding.courses.
Definition and Usage
The :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 the :nth-child(1).
Basic Example
<!-- HTML -->
<ol>
<li>li</li>
<li>li</li>
<li>li</li>
<li>li</li>
</ol>
/* CSS */
li:first-child {
background-color: yellowgreen;
}
Syntax
:first-child {
/* ... */
}
Examples
# Styling the First Heading Element
<!-- HTML -->
<article>
<h2>Heading Element</h2>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</article>
/* CSS */
article h2:first-child {
background-color: yellowgreen;
}
# Styling Nested Elements
<!-- HTML -->
<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>
/* CSS */
article *:first-child {
background-color: yellowgreen;
}
Top comments (0)