CSS & LayoutBaseline · Newly

CSS Nesting & @scope

Mental Model

Native CSS Nesting lets rules nest with & (desugaring under the hood to :is()) without Sass. @scope adds true DOM boundaries ("donut scope") with upper roots and lower to (...) exclusions, plus proximity-based tie-breaking in the cascade.

Interactive Simulator

BEM Naming Conventions vs Native Nesting + @scope

Compare verbose BEM class chains against native & nesting and @scope.

Lines of Code
Before
3
After
6
Reflows / Browser Cost
Before
0 (manual class discipline)
After
0 (native Style)
BeforeFlat BEM Without Boundaries
.card__title { font-weight: 600; }
.card__body .card__title { color: #333; }
/* Leaks into nested sub-cards unless renamed */
Lines: 3Reflows: 0 (manual class discipline)Dependencies: Sass / BEM convention

Requires unique class prefixes to prevent nested theme leaks.

After (Native)Native Nesting + @scope Donut
@scope (.card) to (.card-slot) {
  .title {
    font-weight: 600;
    &:hover { text-decoration: underline; }
  }
}
Lines: 6Reflows: 0 (native Style)Dependencies: 0 build tools

Matches .title inside .card, stops at .card-slot, and requires no BEM prefix.

Under the Hood

Sass nesting is just string concatenation at build time; native CSS Nesting and @scope are live structural rules inside Specificity & Inheritance.

  1. :is() Desugaring: .a, #b { & .c {} } evaluates as :is(.a, #b) .c, giving every match #b's specificity.
  2. Donut Scope: @scope (.card) to (.slot) matches elements inside .card and stops before entering .slot, preventing parent styles from bleeding into slotted children.
  3. Proximity Tie-Breaker: Between two equally specific @scope rules, the one whose scope root is fewer DOM hops away wins, sitting right below Cascade Layers in precedence.
CSS
@scope (.theme-dark) to (.theme-light) {
  a { color: #93c5fd; }
  & .badge { background: #1e293b; }
}

Problem Genealogy

  • 2006–2022: Sass/PostCSS provided nesting, while BEM and CSS Modules simulated scoping via mangled class names.
  • 2023–2026: Native CSS Nesting and @scope moved nesting and DOM-bounded scoping directly into the browser's CSS parser.

Production Pitfalls

Production Pitfall
  • BEM concatenation trap: Unlike Sass, native &__item does not concatenate class names into .card__item; write & .item or separate classes.
  • :is() specificity inflation: Nesting under a comma-separated list containing an ID or class inflates specificity for all branches.
When Not to Use
  • When not to use @scope: Avoid @scope when you want strict shadow-boundary encapsulation of every inherited property; use Shadow DOM instead.

Connections & Logical Next Steps

CSS & LayoutCSS Nesting & @scope
What This Unlocks
Leaf concept

Mechanical Comparisons