CSS: Scope proximity in cascade

By Xah Lee. Date: .

Scope Proximity in the Cascade

the @scope at-rule adds a new cascade criterion called scoping proximity. It sits after specificity and before order of appearance.

Full cascade sorting order (highest to lowest precedence)

  1. Origin + Importance
  2. Cascade layers
  3. Specificity
  4. Scoping proximity
  5. Order of appearance

How scoping proximity works

When two declarations have the same specificity, the one whose scoping root is closer to the element in the DOM tree wins (fewest generational or sibling hops between the element and its scoping root).

Specificity of selectors inside @scope

Inside @scope:

Bare selectors inside @scope adds 0 specificity.

The nesting selector & adds 0 specificity.

:scope adds pseudo-class specificity (0-1-0).

@scope (.card) {
 img {
  /* specificity 0-0-1 */
 }
 :scope img {
  /* specificity 0-1-1 */
 }
 & img {
  /* specificity depends on root; higher if ID used */
 }
}

CSS cascade and scope