Sub topic 3
Selector Lists and Nesting
Assume you know CSS selectors, combinators, specificity, and media queries.
Selector lists and nesting
A selector list contains multiple selectors separated by commas. In a nested rule, the & represents the parent selector:
#main, .note {
& p {
color: red;
}
}This behaves like:
:is(#main, .note) p {
color: red;
}The rule matches paragraphs inside either #main or .note.
How specificity is calculated
Specificity measures how strongly a selector targets an element. An ID contributes (1, 0, 0), a class or pseudo-class contributes (0, 1, 0), and a type selector contributes (0, 0, 1).
For a nested selector list, the parent contributes the specificity of its most specific selector, similar to :is():
#main, .note {
& p {
color: red;
}
}The nested rule has specificity (1, 0, 1): the ID from #main plus the p type selector. This applies even when the paragraph matches through .note.
Declarations after nested rules
Keep ordinary declarations before nested rules. Declarations that follow a nested rule are treated as later declarations, which can change cascade results:
.card {
color: black;
& .title {
color: blue;
}
color: green;
}The final color: green is a separate later declaration for .card. Use a consistent order to make this behavior clear.
What native nesting does not do that Sass does
Sass is a preprocessor. It adds variables, mixins, functions, and compile-time transformations. Native nesting is handled by the browser and does not provide those Sass features. Native CSS also does not automatically create vendor-prefixed output or generate files during a build.
Browser support and fallbacks
Modern browsers support native nesting, but older browsers may ignore nested rules. Keep a flat fallback before the nested version:
.card .title {
font-weight: 600;
}
@supports selector(&) {
.card {
& .title {
font-weight: 600;
}
}
}Keeping nested CSS maintainable
Prefer shallow nesting, usually one or two levels. Deep nesting creates specific selectors that are harder to override. Use classes for components and states, and check the compiled selector and its specificity when a rule behaves unexpectedly.
Exercise
What specificity does #app, .message { & span { color: red; } } produce?
Show answer
(1,0,1), because the parent list uses the most specific option, #app, and the nested selector adds the span type.