Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Native CSS nesting: group states without raising specificity by accident

Last updated: 5 Oct 20265 min read
tutorial
BeginnerBy AITrove Editorial

Native CSS nesting writes a rule inside another rule. The nested selector is resolved relative to the outer selector, so its final match still depends on document structure and the cascade.

How the rule works

A review card has a stable base style, an invalid state, and a heading. Keep those rules close without encoding the whole page wrapper. The ampersand marks where the outer selector participates; it is useful when the state class sits on the same element. A nested descendant selector can omit the ampersand, but a short explicit relationship often reads better during review. Nesting does not create a new component boundary, and a selector list in the parent can affect the expanded specificity. If a rule starts winning unexpectedly, inspect the expanded selector in developer tools rather than adding another layer of nesting. Prefer a flat rule when a nested block becomes harder to scan than the relationship it expresses.

css
.review-card {
  padding: 1.25rem;
  border: 1px solid #a9b9c9;
  &.review-card--invalid { border-color: #a92d3b; }
  > h2 { margin-block: 0 .75rem; }
}

Cost and verification

Nesting removes repeated selector text, not CSS matching work. Its real cost is debugging selector expansion when a file mixes long parent lists, states, and conditional rules. The sample has one state and one direct child; inspect both with the invalid class on the card. Test an older browser only if your audience requires it, and provide a build transform or flat fallback for that support target. Do not assume a CSS preprocessor's nesting syntax and native CSS nesting have identical parsing in every case.

Common Mistakes

  • Do not nest six wrapper levels to mirror one template.
  • Do not expect nesting to lower specificity automatically.
  • Do not place a state class on a child when the selector expects it on the card.

Connected lessons

css
foundations
web
Storage details