How to Select HTML in CSS: 5 Effective Methods
CSS selectors are powerful tools for styling web pages. When targeting the <html> element, developers often overlook creative yet practical approaches. This article explores five methods to select <html> in CSS, from standard techniques to clever workarounds.
1. Using :root for Global Styles
The :root pseudo-class targets the root element of an XML document. In HTML, this matches <html>. It’s ideal for defining global custom properties:
:root {
--primary-color: #333;
}Why use it? :root has higher specificity than element selectors, reducing style conflicts. It’s also versatile for XML-based documents like SVG or RSS feeds.
2. The :scope Pseudo-Class
:scope matches the current scope root. Outside @scope blocks, it behaves like <html>:
:scope {
font-family: sans-serif;
}Pro tip: While semantically similar to :root, :scope aligns better with JavaScript’s globalThis concept for scoping styles.
3. The Ampersand (&) Selector in Nesting
When using CSS nesting, the & symbol references the parent selector. Outside nesting, it selects the scope root (<html>):
& {
background: #fff;
}Gotcha: This works only in CSS nesting contexts. Standalone & selectors are invalid syntax.
4. :has() with <head> or <body>
Use :has() to target <html> via its direct children:
html:has(head) {
color: red;
}Practicality: While valid, this method is rarely useful. HTML documents must contain exactly one <head> and one <body>, making this selector redundant in most cases.
5. The :not(* *) Trick
This selector targets elements not nested within other elements. Since <html> is the top-level element:
:not(* *) {
border: 1px solid black;
}Fun fact: This method creates a “bird” selector (:not(* > *)) that only matches <html>—a quirky but valid CSS experiment.
Conclusion
Mastering <html> selection techniques expands your CSS toolkit. While some methods are practical (like :root), others are clever experiments. Test these approaches in your projects to see which work best.
Call to Action
Experiment with these selectors in your next project. Which method do you prefer for global styles? Share your thoughts in the comments!








