:first-child matches an element that is the first child of its parent. :last-child matches the last.
<style>
ul { list-style: none; padding: 0; width: 220px; border: 1px solid #ccc; }
li { padding: 10px 14px; border-bottom: 1px solid #ccc; }
li:last-child { border-bottom: 0; }
li:first-child { font-weight: bold; background: #fdf2e9; }
</style>
<ul>
<li>First item (bold)</li>
<li>Middle item</li>
<li>Last item (no bottom border)</li>
</ul>
The classic use: no border on the last item
Items usually get a divider line. The last one should not, since the container already has a border. :last-child handles it without any extra class.
Other helpful ones
| Selector | Matches |
|---|---|
:first-child | The first child of its parent |
:last-child | The last child of its parent |
:only-child | The only child |
:first-of-type | The first element of its tag among siblings |
:last-of-type | The last of its tag |
/* Space between siblings but not before the first */
li + li { margin-top: 8px; }
/* Remove the top margin of the first paragraph in a card */
.card > p:first-child { margin-top: 0; }
first-child vs first-of-type
p:first-child means “a p that is the first thing in its parent”. If an h2 comes first, no paragraph matches. p:first-of-type means “the first p among its siblings”, whatever comes before. If a selector surprises you, that is the usual reason.
A comment or text node in front
:first-child.