Avoid specificity traps in native CSS nesting
Keep native CSS nesting predictable by separating an ID from a grouped parent selector that needs a class-level override.
You move a nested Sass rule into plain CSS. The rule matches the same title, but an override that used to win now loses. Check the selectors grouped on the parent rule before adding more specificity to the override.
Reproduce the losing override
Use <section class="panel"><h2 class="title">Summary</h2></section> as the markup. Load a stylesheet with the nested rule and a later override for the panel title.
.panel, #featured {
& .title {
color: navy;
}
}
.panel .title {
color: tomato;
}The title is navy in a browser that supports nesting, even though the element has no featured ID. The & .title rule matches through .panel. The parent selector list determines its weight for the cascade.
For specificity, read the nested selector as :is(.panel, #featured) .title. The ID is the strongest selector inside :is(), so the nested rule has weight (1, 1, 0). The later .panel .title rule has (0, 2, 0). The browser compares the ID count first, so the nested rule wins even though it appears earlier. See how the nesting selector gets its specificity.
Separate selectors with different weights
Replace the stylesheet with this version. It moves the ID to its own rule and keeps the panel selector nested.
.panel {
& .title {
color: navy;
}
}
#featured .title {
color: navy;
}
.panel .title {
color: tomato;
}The panel title now uses tomato. Both panel selectors weigh (0, 2, 0), so the later one wins. A title under #featured still matches the stronger ID rule, which keeps it navy even when the same section has the panel class.
You can omit the ampersand for a simple descendant like .title. The outer selector list still determines the shared weight, even with an implicit descendant.
Check the actual element that lost
Use the Styles panel on an element that matches the class branch without the ID. Compare the two rules using IDs, classes and type selectors in that order. If the nesting group contains an ID, split it out and check the computed color again.
With a large legacy selector list, flattening into separate selectors also gives each branch its own weight. Use that for the mixed list, then keep nesting where the grouped selectors should share the same weight.