Episode 20 of 53
First and Last Child Selector
Learn how to target the first and last child elements using :first-child and :last-child.
The :first-child and :last-child pseudo-classes let you target elements based on their position among siblings.
:first-child
/* Target the first <li> in any list */
li:first-child {
font-weight: bold;
color: #2c3e50;
}
/* Target the first <p> in a container */
.content p:first-child {
font-size: 1.2rem;
color: #555;
}
:last-child
/* Remove bottom border from the last list item */
li:last-child {
border-bottom: none;
}
/* Remove bottom margin from the last paragraph */
.content p:last-child {
margin-bottom: 0;
}
Practical Example
<ul class="nav">
<li>Home</li> <!-- matched by li:first-child -->
<li>About</li>
<li>Contact</li> <!-- matched by li:last-child -->
</ul>
.nav li {
padding: 0.75rem 1rem;
border-bottom: 1px solid #eee;
}
.nav li:first-child {
border-top-left-radius: 8px;
border-top-right-radius: 8px;
}
.nav li:last-child {
border-bottom: none;
border-bottom-left-radius: 8px;
border-bottom-right-radius: 8px;
}
Important Note
:first-child selects an element only if it is the first child of its parent, regardless of element type. We'll cover :first-of-type in the next episode.