Skip to main content

On This Page

Beyond the Element Selector: Advanced and Obscure Ways to Target the HTML Root

2 min read
Share

These articles are AI-generated summaries. Please check the original sources for full details.

The Different Ways to Select in CSS

Daniel Schwarz explores the diverse methods available to target the root element in modern CSS. While the standard element selector is common, pseudo-classes like :root and :scope offer different specificity levels.

Why This Matters

Selecting the root element is essential for defining global custom properties and managing top-level layout. Understanding the differences in specificity—such as :root’s (0-1-0) vs. the element selector’s (0-0-1)—prevents unintended style overrides in complex stylesheets. This technical distinction allows for more robust architecture when managing design systems.

Key Insights

  • The :root pseudo-class matches the root element of XML documents, targeting in HTML and in SVG documents.
  • Pseudo-classes like :root carry a specificity of 0-1-0, which is higher than the 0-0-1 specificity of the standard html element selector.
  • The :scope selector matches the global scope root () unless used within an @scope at-rule to define a custom scope.
  • When the & nesting selector is used outside of a nested block, it defaults to selecting the scope root.
  • The selector :not(* *) targets because it is the only element not contained by another element.

Working Examples

Defining global custom properties using the :root pseudo-class.

:root { --color: black; }

Selecting the only element not contained by another: the root.

:not(* *) { color: blue; }

Practical Applications

  • Use Case: Declaring global custom properties on :root to leverage higher specificity and document-wide scope.
  • Pitfall: Using :has(head) or :not(* *) results in ‘useless’ complexity that reduces code maintainability without providing functional benefits.

References:

Continue reading

Next article

The Economics of Reliability: Balancing Infrastructure Costs and Catastrophic Risk

Related Content