The Hidden Selectors of The HTML Element
How would you select the <html> element? Using the classic and well-known html {} and :root {}, right? What if I tell you there are other hidden selectors?
Let's start with the shortest selector, the nesting selector. A one-character selector:
& {
font-size: 20px;
background: lightblue;
}
The next one is the :scope selector
:scope {
font-size: 20px;
background: lightblue;
}
For those selectors, I am relying on their fallback behavior. The nesting selector & will behave the same as :scope when not used inside a nested rule and :scope represents the root of the document when there is no scoping root.
The <html> element is the only element having head and body as child elements, so we can use the :has() selector like below:
:has(head) {
font-size: 20px;
background: lightblue;
}
/* OR */
:has(body) {
font-size: 20px;
background: lightblue;
}
The <html> element is the only element without a parent, so here is another fancy selector using :not()
:not(* *) {
font-size: 20px;
background: lightblue;
}
Let's add the child combinator (>) to have two eyes and a nose!
:not(* > *) {
font-size: 20px;
background: lightblue;
}
We can also have more combinations like below:
:is(&) {}
:where(&) {}
&& {}
&&&& {} /* Yes, you can append as many "&" as you want! */
:has(> body)
:has(> head)
:has(body,head)
/* etc... */
Are they useful? Probably not, but it's a fun exercise to explore CSS Selectors.
More CSS Tips
- Direction-Aware CSS Shapes A few lines of code to make any CSS shape adjust according to the direction of the text.
- Direction-Aware Arrow Shape using corner-shape Combining corner-shape and logical properties to create direction-aware shapes..