Structural Pseudo-Classes: :nth-child(), :nth-of-type(), of S and Friends
Selecting elements by their position among siblings: :first-child, :last-child and :only-child, the of-type variants, :nth-child() with an+b formulas, odd and even, the of S filter, :nth-last-child(), quantity queries, :root and :empty, and the common mistakes with each.
kvi5hnuCode Sprout team member10 min readOn this page
Pseudo-classes select elements by something that isn't written as a class or attribute: their position, their state, or what they contain. They start with a single colon, such as :first-child or :hover, and can be added to any compound selector. This article covers the structural pseudo-classes, which select elements by their position in the document tree: the first item of a list, every other table row, the last paragraph of an article. Because they're computed from the document, they update automatically when items are added or removed, with no classes to maintain.
A pseudo-class describes the element it's attached to
The most common misunderstanding is reading p:first-child as "the first child of a paragraph". It means a paragraph that is itself the first child of its parent. A pseudo-class adds a condition to the element it's attached to, as an invisible class would:
li:first-child { } /* an li that is the first child of its parent */
.menu > :first-child { } /* the first child of .menu, whatever its type */
.menu :first-child { } /* every element inside .menu that is a first child, at any depth */
To style the first child of an element, put the pseudo-class on the child, after a combinator: .menu > :first-child.
Pseudo-classes can be chained, and every condition must hold: li:first-child:hover is the first item, while it's hovered. Their order doesn't matter, but they must come after a type selector, and before a pseudo-element.
First, last and only
| Pseudo-class | Matches an element that... |
|---|---|
:first-child | is the first element child of its parent |
:last-child | is the last element child of its parent |
:only-child | is its parent's only element child |
:first-of-type | is the first of its element type among its siblings |
:last-of-type | is the last of its element type among its siblings |
:only-of-type | is the only one of its element type among its siblings |
Only elements count as children. Text and comments between them are ignored, so in <p>Read <a>this</a> now</p>, the link is the paragraph's only child.
li:first-child { font-weight: 700; }
li:last-child { color: #8a3b12; }
li:only-child { font-style: italic; color: #2f7d4f; }
The single staff pick is a first child, a last child and an only child at the same time, so all three rules apply to it. Its color comes from :only-child, the later rule.
-child versus -of-type
The -child pseudo-classes count all element siblings. The -of-type ones count only siblings of the same element type:
<article>
<h2>Events</h2>
<p>First paragraph</p>
<p>Second paragraph</p>
</article>
Here p:first-child matches nothing, because the first child is the h2. p:first-of-type matches "First paragraph", the first p among the siblings.
"Type" means the element name, never a class. In <p class="intro">A</p><p>B</p>, the selector .intro:only-of-type matches nothing: the p with class intro isn't the only p. Counting by class is what the of S syntax below is for.
:nth-child() and the an+b formula
:nth-child() takes an argument that says which positions to match:
| Argument | Matches positions |
|---|---|
3 | 3 only |
odd (same as 2n+1) | 1, 3, 5, ... |
even (same as 2n) | 2, 4, 6, ... |
3n | 3, 6, 9, ... |
3n+1 | 1, 4, 7, ... |
n+4 | 4, 5, 6, ... (from the 4th on) |
-n+3 | 3, 2, 1 (the first three) |
2n+3 | 3, 5, 7, ... |
The formula is an+b: the browser substitutes n = 0, 1, 2, 3... and matches the positions that come out as positive whole numbers. Positions count from 1.
ais the step andbis the offset.3n+1is every third element, starting at the first.- A negative
acounts down:-n+3gives 3, 2, 1, 0, −1..., so it selects the first three. That's the standard way to select "the first N". - A negative
bis written with a minus:3n-1(2, 5, 8...).3n+-1is invalid. - Spaces are allowed around the
+or-but not inside a number andn:3n + 1is fine,3 nisn't.

The last panel combines two formulas on one element: n+4 sets the lower bound and -n+8 the upper one, so only positions in both sets match.
table { border-collapse: collapse; font-family: system-ui, sans-serif; }
td { padding: 0.25rem 0.75rem; }
tr:nth-child(even) { background: #f4efe6; }
tr:nth-child(-n + 3) td:first-child { font-weight: 700; color: #8a3b12; }
Change -n + 3 to n + 4 to bold everything from the fourth row on, or even to 3n to shade every third row.
:nth-child(1) is exactly the same as :first-child. Use whichever reads better.
:nth-last-child(), :nth-of-type() and :nth-last-of-type()
:nth-last-child(an+b)counts from the end::nth-last-child(1)is the last child, and:nth-last-child(-n+2)is the last two.:nth-of-type(an+b)counts only siblings of the same element type:p:nth-of-type(2)is the second paragraph, however many other elements come between.:nth-last-of-type(an+b)counts the same type from the end.
The difference between -child and -of-type matters in mixed content, such as a table row with a header cell:
<tr><th>Price</th><td>€12</td><td>€18</td><td>€9</td></tr>
td:nth-child(2) is the first td (position 2 among all children). td:nth-of-type(2) is the second td, "€18".

Compare p:nth-child(3) with p:nth-of-type(3): the same number picks different paragraphs, because the first counts the h2 and the div and the second doesn't.
Filtering with of S
:nth-child() and :nth-last-child() accept an optional of S part: a selector list that filters which siblings are counted. Only siblings matching S are numbered, and the element must match S too:
li:nth-child(2 of .available) { } /* the second li that has class available */
tr:nth-child(even of :not([hidden])) { } /* stripes that stay correct when rows are hidden */
This solves a classic problem. With plain :nth-child(even), hiding a row (for example when filtering a table) shifts every stripe after it, because hidden rows are still counted. Counting only visible rows keeps the stripes alternating:
ul { list-style: none; padding: 0; width: 18rem; font-family: system-ui, sans-serif; }
li { padding: 0.3rem 0.6rem; }
.plain li:nth-child(even) { background: #f4efe6; }
.smart li:nth-child(even of :not([hidden])) { background: #f4efe6; }
.wrap { display: flex; gap: 1rem; }
The left list shades only History: the hidden item still takes position 2, so Fiction and Poetry end up next to each other with no stripe between them. The right list counts only the visible items and shades Poetry and Travel, so the stripes alternate.
Only :nth-child() and :nth-last-child() take of S: p:nth-of-type(2 of .x) is invalid. The selector list also adds its specificity, so :nth-child(2 of .available) counts as two classes (article 15).
of S isn't the same as putting the selector outside: li.available:nth-child(2) means "the second child, if it has class available", while li:nth-child(2 of .available) means "the second of the available items".
Quantity queries
Combining :nth-child() and :nth-last-child() lets you style elements based on how many siblings there are. An element that's both first and the third from last is the first of exactly three:
/* exactly three items: style all of them */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li { width: 33.33%; }
/* five or more items: switch to a compact style */
li:first-child:nth-last-child(n + 5),
li:first-child:nth-last-child(n + 5) ~ li { font-size: 0.875rem; }
With :has() (article 12), the same idea is easier to write on the parent: ul:has(> li:nth-child(5)) matches a list with at least five items. Flexbox and grid also adapt to the number of items on their own, so quantity queries are needed less often than they used to be.
:root
:root matches the root element of the document, which in HTML is always <html>. It's the conventional place for global custom properties:
:root {
--brand: #8a3b12;
--space: 1rem;
}
:root and html select the same element in HTML, but :root has the specificity of a class, while html has that of a type selector (article 15). In an SVG file, :root is the outer <svg> element.
:empty
:empty matches elements with no children at all: no elements and no text, not even whitespace. Comments don't count:
<p></p> <!-- :empty -->
<p><!-- note --></p> <!-- :empty -->
<p> </p> <!-- not :empty: a space is text -->
<p>
</p> <!-- not :empty: a newline is text -->
That makes :empty fragile with templates that add whitespace. It's still useful for hiding containers a CMS or script may leave empty, such as .error-message:empty { display: none; }, as long as the template outputs nothing between the tags.
Void elements such as <img>, <input> and <br> are always :empty, since they can't have children. Drafts of Selectors Level 4 proposed letting :empty ignore whitespace, but no browser implemented that, so whitespace still counts.
What's current
:nth-child(an+b of S)became Baseline widely available in November 2025. It works in all current browsers.- The other structural pseudo-classes have been supported everywhere for many years.
- Elements without a parent, such as the root element, can match
:first-child,:last-child,:only-childand:nth-child(), as Selectors Level 4 defines. Chrome and Firefox do this for all of them; Safari only for:only-child(since 17). It rarely matters in practice. - Equivalent forms differ in specificity.
:first-child:last-childmatches the same elements as:only-child, and:nth-child(1)the same as:first-child, but the chained forms count as two pseudo-classes.
Common questions
Why doesn't p:first-child select the first paragraph in my article?
Because the first child is something else, usually a heading. :first-child requires the element to be its parent's first child of any type. Use p:first-of-type, or h2 + p for the paragraph right after the heading.
How do I select the first element with a certain class?
:first-of-type doesn't help, since it works by element name. Use :nth-child(1 of .class). For "every .class except the first", use .class ~ .class.
How do I select the last three items?
li:nth-last-child(-n + 3). For the first three, li:nth-child(-n + 3).
Does :nth-child() count text between elements?
No. Only element siblings are counted. Text, whitespace and comments don't affect positions.
Do structural pseudo-classes update when JavaScript adds or removes elements?
Yes. They're recomputed whenever the tree changes, so new rows get the right stripe and the new last item becomes :last-child. That's their advantage over classes such as odd and last, which a script has to keep updated.
Is :nth-child() slow?
No. Browsers cache sibling positions. It's fine even on long lists and tables.
Summary
- Pseudo-classes add conditions to the element they're attached to:
p:first-childis a paragraph that is a first child. :first-child,:last-childand:only-childcount all element siblings. The-of-typeversions count siblings with the same element name, never classes.:nth-child(an+b)matches positions from the formula withn = 0, 1, 2...:odd,even,3n+1,-n+3for the first three,n+4from the fourth.:nth-last-child()and:nth-last-of-type()count from the end.:nth-child(an+b of S)numbers only siblings that matchS, which fixes zebra stripes with hidden rows and selects the nth item with a class.- Combining first and nth-last positions gives quantity queries, though
:has()is often simpler now. :rootis the<html>element with class-level specificity, and:emptymatches elements with no children, not even whitespace.
Practice questions
Which list items does each selector match in a list of eight items? li:nth-child(3n), li:nth-child(3n+2), li:nth-child(-n+2), li:nth-last-child(2).
Answer
3n: items 3 and 6. 3n+2: items 2, 5 and 8. -n+2: items 1 and 2. nth-last-child(2): item 7, the second from the end.
In this markup, which elements match p:first-of-type and which match p:first-child?
<section>
<h3>Readings</h3>
<p>Thursday</p>
<p>Saturday</p>
</section>
Answer
p:first-of-type matches "Thursday", the first p among the siblings. p:first-child matches nothing, because the section's first child is the h3.
Write a selector for the second li that has the class in-stock, whatever other items come before it.
Answer
li:nth-child(2 of .in-stock). Writing li.in-stock:nth-child(2) would instead require the second child overall to have the class.
Does .notice:empty match <div class="notice"> </div>? How could you make the empty-notice rule robust?
Answer
No. The space is a text node, so the element isn't empty. Make the template output <div class="notice"></div> with nothing between the tags. Alternatively, style the notice only when it contains something specific, for example .notice:not(:has(*)) for "no child elements", which ignores whitespace (article 12).
Previous: Combinators: Descendant, Child, Next-Sibling and Subsequent-Sibling Selectors

More in CSS Course
Quiz: CSS Delicate Details
Twenty-five questions on the edge cases that surprise experienced developers: invalid custom properties, shorthands that reset values, layer order with !important, containing blocks, margin collapsing, specificity of :is() and :where(), intrinsic minimum sizes, and more, each checked in Chrome.
Quiz: CSS Interview Questions
Thirty front-end interview questions: cascade, specificity and layers, box model and margin collapsing, stacking contexts, positioning, flexbox and grid, responsive design, custom properties, performance, accessibility, modern selectors and architecture.
Quiz: CSS Course Final Exam
Thirty questions across the whole CSS course: syntax and error handling, selectors, the cascade and layers, values and units, color, the box model, backgrounds, positioning, flexbox, grid, responsive design, typography, generated content, effects, transforms, motion and architecture.
Quiz: CSS Architecture, Tooling and Debugging (CSS Part 17)
Twenty questions on modular CSS and BEM, layering a stylesheet, design tokens and theming, pattern libraries and safe refactoring, preprocessors and build tools, the at-rules reference, and debugging common CSS problems.
Discussion
Sign in to ask a question or share what you learned.