Native CSS Nesting
Write Sass-style nested rules in plain CSS — no build step — and avoid the two gotchas that trip everyone up.
For years nesting was the number one reason people reached for Sass. Now it's baked into CSS itself and shipping in every evergreen browser. You nest a rule inside another and it's scoped to the parent.
.card {
padding: 1rem;
border-radius: 12px;
h3 { margin: 0; }
&:hover { box-shadow: 0 8px 20px rgba(0,0,0,.15); }
& .badge { color: crimson; }
}The & nesting selector
The ampersand means “the parent”. Use it for pseudo-classes (&:hover), for compound selectors (&.is-active), and any time the nested selector must attach to the parent rather than describe a descendant.
Two things that will bite you
- A bare nested selector like
h3 { }is treated as a descendant (.card h3). If you want the parent itself in a compound, you must write&. - You can't nest a selector that starts with an element name directly against the parent without
&in older implementations — today it's fine, but writing&explicitly keeps your intent unambiguous.
Example
When to use it
- A developer nests .card .title and .card:hover rules inside .card to keep all card-related styles in one block, eliminating scattered selectors.
- A designer nests media queries inside a component rule so responsive overrides stay co-located with the component's base styles.
- A developer uses & in a nested rule to generate .btn.active instead of a descendant selector, controlling when the nesting ampersand is needed.
More examples
Nested component rules
Nests .title and :hover inside .card so all related styles are co-located without repeating the parent selector.
.card {
background: #fff;
padding: 20px;
border-radius: 8px;
.title {
font-size: 1.25rem;
color: #1a1a2e;
}
&:hover {
box-shadow: 0 8px 24px rgba(0,0,0,0.12);
}
}Nested media query in component
Places the media query breakpoint override inside the component rule so responsive styles stay with their base definition.
.hero {
font-size: 1.5rem;
padding: 32px 16px;
@media (min-width: 768px) {
font-size: 2.5rem;
padding: 80px 24px;
}
}Ampersand for modifier class
Uses & to create modifier and state selectors that combine with .btn rather than descending into it.
.btn {
background: #2965f1;
color: #fff;
/* generates .btn.btn-danger, not .btn .btn-danger */
&.btn-danger {
background: #c0392b;
}
/* generates .btn:disabled */
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
}
Discussion