:where 伪类

最近在将手上的项目从 Ant Design 从 v4 升级到 v5 后,发现 Ant Design 使用了 css-in-js 方案,观察了下输出的产物,Ant Design 对其生成的 css-hash 类加了 :where(.css-[hash]) 这样的伪类。遂学习了下这个 css 伪类。

特性

主要有 2 点特性:

  1. :where 和它的兄弟伪类 :is 可接受 可容错选择器列表,即 :where([selector list])selector 部分中,有无效的选择器时,不影响其他的选择生效。
  2. :where 中的选择器优先级权重为 0,即 :where(.class-1).class-a 这样的选择器,实际权重与 .class-a 是一致的。

使用原因

Ant Design 5 选择使用 :where 伪类来包裹 css-in-js 产物的原因是忽略新增 css-hash 的优先级,防止使用方在从 4 升级到 5 过程中因为新增的 css-hash 产生的权重影响了原先的定制样式。

:is

前面提到了 :is,它和 :where 伪类基本一致,唯一的区别在于它会计算优先级权重,而不像 :where 一样是 0。

兼容性

chrome 88+ 支持