HTML元素的隐藏选择器
December 04, 2025
2025年12月04日
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?
你会如何选择 <html> 元素?使用经典且众所周知的 html {} 和 :root {},对吧?如果我告诉你还有其他隐藏的选择器呢?
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 选择器
: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.
对于那些选择器,我依赖于它们的回退行为。嵌套选择器 & 在未在嵌套规则内使用时将表现得与 :scope 相同,而 :scope 在没有作用域根时表示文档的根。
The <html> element is the only element having head and body as child elements, so we can use the :has() selector like below:
<html> 元素是唯一具有 head 和 body 作为子元素的元素,因此我们可以像下面这样使用 :has() 选择器:
:has(head) { font-size: 20px; background: lightblue;}: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()
<html> 元素是唯一没有父元素的元素,所以这里有另一个使用 :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(&) {}&& {}&&&& {} :has(> body):has(> head):has(body,head)
Are they useful? Probably not, but it's a fun exercise to explore CSS Selectors.
它们有用吗?可能没有,但探索 CSS 选择器是一个有趣的练习。
- Direction-Aware CSS Shapes A few lines of code to make any CSS shape adjust according to the direction of the text. November 27, 2025
- 方向感知 CSS 形状 几行代码使任何 CSS 形状根据文本的方向进行调整。2025年11月27日
- Direction-Aware Arrow Shape using corner-shape Combining corner-shape and logical properties to create direction-aware shapes.. November ...