Sub topic 5
Selecting by position: :first-child, :last-child, :only-child, :empty, :root
This chapter assumes you know basic HTML elements and attributes, CSS rule syntax, type, class, ID and attribute selectors, and the descendant and child combinators. It also assumes you know that a pseudo-class starts with one colon, as covered earlier in this series.
What structural pseudo-classes do
A structural pseudo-class matches an element because of where it sits in the document tree, not because of a class or attribute you gave it. This lets you style the first item, the last item, or an empty container without editing the HTML.
Every selector in this chapter looks only at element nodes. Text nodes are ignored when counting positions. They matter in one place only: :empty.
| Selector | Matches an element when |
|---|---|
| `:first-child` | it is the first element child of its parent |
| `:last-child` | it is the last element child of its parent |
| `:only-child` | it is the only element child of its parent |
| `:empty` | it has no children at all, including text |
| `:root` | it is the root element of the document |
:first-child and :last-child
:first-child selects an element that is the first element inside its parent. :last-child does the same for the final one. The most common use is removing a separator that only belongs between items:
.menu li {
border-bottom: 1px solid #ddd;
padding: 0.5rem 0;
}
.menu li:last-child {
border-bottom: 0;
}Every li gets a bottom border, and the last one overrides it. If you add or remove items later, the rule still works.
The type is not part of the position
The most common error is reading p:first-child as "the first paragraph". It means "an element that is a p and is also the first child of its parent." Both conditions must hold.
<article>
<h2>Title</h2>
<p>Intro</p>
<p>Body</p>
</article>article p:first-child {
font-size: 1.25rem;
}This rule matches nothing. The first child of article is the h2, so no p qualifies. To target the first paragraph here, use the adjacent sibling combinator, h2 + p. Or use p:first-of-type, which a later chapter covers.
Combining with a class
You can attach a class and a pseudo-class to the same compound selector: .card.featured:first-child. Write them with no spaces. A space would turn it into a descendant combinator, and .card .featured:first-child means something different.
:only-child
:only-child matches an element that has no element siblings. It is equivalent to :first-child:last-child. It is useful when the layout depends on how many items exist:
.tags li {
display: inline-block;
margin-right: 0.5rem;
}
.tags li:only-child {
font-weight: bold;
}A single tag gets bold text. Once a second tag is added, the rule stops matching. The browser re-evaluates it whenever the DOM changes, including changes made by JavaScript.
:empty
:empty matches an element with no children. Children here include text nodes, so the check is stricter than "looks empty".
<span class="badge"></span>
<span class="badge"> </span>
<span class="badge"><!-- note --></span>
<span class="badge">3</span>.badge {
background: #c00;
color: #fff;
padding: 0.1rem 0.5rem;
border-radius: 1rem;
}
.badge:empty {
display: none;
}- The first badge matches and is hidden.
- The second does not match. A single space is a text node, so the element is not empty.
- The third matches. Comments do not count as children for
:empty. - The fourth does not match because it contains text.
Elements that cannot have children, such as img, br, and input, always match :empty. Write .badge:empty, not a bare :empty, so you do not hide elements by accident.
A practical use is collapsing an optional container, such as an error message area that the server fills only when something went wrong. The :empty rule hides it so its padding and border do not leave a blank box.
:root
:root matches the root element of the document. In HTML that is the html element. In an SVG file opened directly, it is the svg element.
Its main use is declaring custom properties (CSS variables) that the whole page inherits:
:root {
--accent: #1a73e8;
--space: 1rem;
}
body {
margin: 0;
padding: var(--space);
}
a {
color: var(--accent);
}In an HTML document, :root and html select the same element. They differ in specificity. html is a type selector, so it counts as (0,0,1). :root is a pseudo-class, so it counts as (0,1,0) and wins when both set the same property. The next chapters return to specificity in detail.
Specificity and dynamic behavior
Each pseudo-class in this chapter adds the weight of one class selector, (0,1,0). So li:last-child is (0,1,1), which is the same weight as li.last. This surprises people who assume pseudo-classes are weaker than classes.
That weight explains an override bug. Suppose you write:
.menu li:last-child {
border-bottom: 0;
}
.menu li.divider {
border-bottom: 2px solid #999;
}Both selectors have the same specificity (0,2,1), so the later rule wins. If the last item also has the divider class, the border returns. Reordering the rules or adding a more specific selector fixes it.
Because these pseudo-classes follow the live DOM, they update as the page changes. If JavaScript appends a new li, the previous last item stops matching :last-child, and the new one starts matching.
Common errors
- Expecting the type to filter the position.
h2:first-childfails if anything precedes theh2in its parent, even ap. - Forgetting that only elements count. A text node before the first element does not stop
:first-childfrom matching. - Using
:emptyon elements that contain whitespace. - Leaving out the parent context.
li:first-childmatches the firstliof every list on the page. Scope it, for example.menu > li:first-child. - Using
:rootselectors for page-wide styles that belong onbody, when only variables need to be global.
Summary of when to choose which
Use :first-child and :last-child for edge decoration such as separators and margins. Use :only-child for layouts that change when a collection has one member. Use :empty to hide containers that may have no content. Use :root for global custom properties and document-level defaults.
Exercise
Given <div class="box"><h3>Heading</h3><p>Text</p></div>, does .box p:first-child match the paragraph? Why or why not, and what selector would match it using a combinator?
Show answer
No. The first element child of .box is the h3, so the p is not a first child. The adjacent sibling selector .box h3 + p matches the paragraph.
Exercise
Which of these <p class="note"> elements does .note:empty match? (a) <p class="note"></p> (b) <p class="note">\n</p> (c) <p class="note"><!-- todo --></p> (d) <p class="note"><b></b></p>`
Show answer
It matches (a) and (c). Option (b) contains a whitespace text node, and (d) contains a child element, so neither is empty.