Sub topic 13
Keeping Nested CSS Maintainable
Native nesting makes it easy to write CSS that mirrors your markup. That convenience can produce long, brittle selectors that are hard to override. This chapter gives practical rules for deciding how much to nest, where conditions belong, and how to deal with browsers that lack support.
What this chapter assumes
You should already know the following:
- How the
&nesting selector works, including the relaxed syntax where&is optional. - How compound selectors (
&.is-open) and parent-context selectors (.dark-theme &) behave. - How nested at-rules such as
@mediawork inside a style rule. - That a nested rule behaves like
:is()when the parent is a selector list.
Nesting produces long selectors
A nested rule is not a new kind of selector. The browser combines the parent and child into one complex selector, exactly as if you had written it out. Each level of nesting adds one more part to that selector.
.page {
.content {
.article {
.body {
p {
line-height: 1.6;
}
}
}
}
}This is equivalent to .page .content .article .body p. Its specificity is (0,4,1): four classes and one type selector. The rule also depends on a five-level chain of markup. If you move .body out of .article, the style stops applying and nothing warns you.
Compare it with a version that anchors the style to the component that owns it:
.article-body {
p {
line-height: 1.6;
}
}The selector is now .article-body p, with specificity (0,1,1). It is shorter, easier to override, and does not care what sits above .article-body in the page.
Specificity accumulates
Every class you add to a selector chain makes it harder for later, simpler rules to win. Consider a theme file that tries to change the title color:
.card {
.body {
.title {
color: black;
}
}
}
/* In a later stylesheet */
.title {
color: royalblue;
}The second rule has specificity (0,1,0). The first has (0,3,0). The first rule wins, even though it comes earlier in the cascade. To override it you would have to repeat the whole chain or reach for !important.
Selector lists make this worse. When the parent is a list, & behaves like :is(), which takes the highest specificity in the list:
#main, .note {
& p {
color: red;
}
}This behaves like :is(#main, .note) p, which has specificity (1,0,1). The .note p case gets the ID-level weight too, even though .note is only a class. Avoid putting an ID in a parent selector list, because the inflated weight applies to every item in it.
Rules of thumb for depth
These are guidelines, not language rules. Adjust them to your team.
- Stay within two or three levels. If you need a fourth level, ask whether the inner part deserves its own class.
- Nest by component, not by page structure. The root of a nested block should be the thing that owns the styles, such as
.cardor.nav. - Prefer class selectors for inner parts. Nested type selectors like
divorspanare fragile because markup changes often. - Use
&for states and modifiers.&:hover,&:focus-visible,&.is-open, and&[aria-expanded="true"]read well because they describe the same element. - Do not nest only to save typing. If two rules are unrelated, write them separately.
- Keep each block short enough to read at once. If a nested block scrolls off the screen, split it.
Here is a component that follows these rules:
.card {
padding: 1rem;
border: 1px solid #ccc;
.title {
font-weight: 600;
}
.actions {
display: flex;
gap: 0.5rem;
}
&:hover {
border-color: #666;
}
&.is-featured {
border-color: gold;
}
}Every nested rule is one level deep, each selector has at most two classes, and the states sit next to the base styles.
A decision flow for each nested rule
When you are about to nest a rule, ask these questions in order.
Keep conditions next to what they change
Nested @media, @supports, and @container rules let you keep a responsive change beside the declaration it modifies. Inside a style rule, declarations in the at-rule apply to the parent selector:
.panel {
display: block;
padding: 1rem;
@media (min-width: 40rem) {
display: grid;
grid-template-columns: 1fr 2fr;
padding: 2rem;
}
}This is easier to maintain than a distant media query block, because anyone editing .panel sees all of its variations. The pattern has limits:
- Keep each conditional block small. If a media query restyles many unrelated components, a single top-level
@mediathat holds several rules may be clearer. - Do not stack many conditions inside one rule. Two or three is readable. Beyond that, split the component into variants.
- Be consistent. Pick either "conditions inside the component" or "conditions grouped at the end of the file", and use that choice throughout a project.
Nested @layer is also valid, but layers are usually clearer at the top level, because layer order is a project-wide decision. Wrapping whole components in a named layer is a good way to control specificity without shortening selectors:
@layer components {
.card {
padding: 1rem;
&:hover {
border-color: #666;
}
}
}Unlayered styles beat layered styles regardless of specificity, so a small override outside the layer wins over deeply nested rules inside it.
Do not try to build names with &
Sass lets you write &__title or &-large to create new class names. Native nesting does not do string concatenation. & stands for a whole selector, so &__title is invalid and the rule is dropped.
/* Invalid in native CSS: & is not a string prefix */
.card {
&__title {
font-weight: 600;
}
}
/* Valid: write the full class name */
.card__title {
font-weight: 600;
}
/* Also valid: nest it as a descendant of .card */
.card {
.card__title {
font-weight: 600;
}
}If you use BEM-style names, write each class in full. This also makes the names searchable: a text search for card__title finds the rule.
Put declarations before nested rules
CSS allows declarations after nested rules, and current browsers keep them in source order. Older implementations moved such declarations as if they had appeared first, which could change which value won. To avoid any ambiguity:
- Put all of a rule's own declarations at the top.
- Follow them with nested rules, then nested at-rules.
- Leave a blank line before the first nested rule.
.alert {
padding: 1rem;
color: #222;
&.is-error {
color: #900;
}
@media (prefers-reduced-motion: no-preference) {
transition: background-color 0.2s;
}
}Browser support and fallbacks
Native nesting works in current versions of Chrome, Edge, Safari, and Firefox. The relaxed syntax, where you can omit & before type selectors such as a or p, shipped later than the first version of nesting. Early implementations required & in front of a nested type selector. For that reason, some teams write & p instead of p while they still support older browser versions.
When a browser does not understand nesting, it treats the nested blocks as invalid and drops them. Your page is not broken at the parser level, but those styles are missing. You have three options:
- Accept it. If your analytics show that unsupported browsers are a tiny share of traffic, ship nesting directly.
- Flatten at build time. Tools such as PostCSS (with a nesting plugin) or Lightning CSS can turn nested CSS into flat CSS. You write nested code and ship flat code.
- Keep critical styles flat. Write layout and readability basics without nesting, and use nesting for enhancements.
A build step also gives you a safety net for the specificity behavior. Test the flattened output in a real browser, because converting :is() semantics to plain selectors can change specificity in some tools.
Review checklist
Before merging nested CSS, check each item:
- No nested block goes deeper than three levels without a reason.
- Inner parts have class selectors, not bare
divorspan. - No ID appears in a parent selector list.
- Every
&is intentional:&:hover,&.modifier, or.context &. - Declarations come before nested rules.
- No
&-suffixor&__suffixnames appear. - Conditional at-rules contain only declarations that belong to the parent.
Exercise
This rule is hard to override. What selector does it produce, what is its specificity, and how would you rewrite it? .layout { .sidebar { .menu { ul { li { a { color: gray; } } } } } }
Show answer
It produces .layout .sidebar .menu ul li a, with specificity (0,3,3): three classes and three type selectors. A later rule like .menu a { color: blue; } has (0,1,1) and loses. Rewrite it around the component and give the link a class: .menu { .link { color: gray; } }, which gives .menu .link (0,2,0). Use .menu-link { color: gray; } if you want an even lower specificity of (0,1,0).
Exercise
Why is .btn { &-primary { background: blue; } } not a valid way to define a .btn-primary class in native CSS, and what should you write instead?
Show answer
Native & represents a complete selector and cannot be joined to a text suffix, so &-primary is invalid and the rule is dropped. Write .btn-primary { background: blue; } as its own rule, or .btn { &.btn-primary { background: blue; } } if you want it to apply only to elements that have both classes.
Exercise
Given #main, .note { & p { color: red; } }, what is the specificity of the selector when it matches <div class="note"><p>…</p></div>, and why?
Show answer
(1,0,1). The nested selector behaves like :is(#main, .note) p, and :is() takes the specificity of its most specific argument, which is the ID. That weight applies even when the match comes through .note.