Structural Pseudo-classes: nth-child and Friends
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
What Structural Pseudo-classes Do
These pseudo-classes select elements based on their position among sibling elements, without needing any class added to the markup at all.
nth-child() Basics
li:nth-child(odd) {
background: #f5f5f5; /* classic striped table/list rows */
}
li:nth-child(3) {
font-weight: bold; /* exactly the third item */
}
li:nth-child(3n) {
color: red; /* every third item: 3, 6, 9... */
}nth-child() accepts a keyword (odd/even), a specific number, or a formula like 3n (a multiple of 3) or 3n+1 (a multiple of 3, plus one).
first-child, last-child and only-child
| Selector | Matches |
|---|---|
:first-child | An element that is the first child of its parent |
:last-child | An element that is the last child of its parent |
:only-child | An element that is the only child of its parent |
The -of-type Variants
p:first-of-type {
font-size: 1.2rem;
}:first-child only matches if the element is literally the first thing inside its parent, regardless of tag. :first-of-type instead matches the first element of that specific tag - useful when a paragraph is preceded by a heading, since p:first-child would fail to match in that case, but p:first-of-type still would.
Excluding Matches with :not()
li:not(:last-child) {
border-bottom: 1px solid #eee; /* a divider between items, but not after the last one */
}Combining structural pseudo-classes with :not() is a very common pattern for adding dividers or spacing between list items without affecting the very first or last one.