前端CSS-伪类选择器函数 :is() and :where()

在写CSS时,有时您可能会以较长的选择器列表来定位具有相同样式规则的多个元素。 例如,如果你想对标题元素h中的所有 <b> 标签设置红色,你可以这样写:

如果使用:where函数或者:is函数,会减少很多代码量,如下:


:where() 和 :is() 之间的区别在于 :where() 始终具有 0 权值,而 :is() 在其参数中使用权重最大的值作为所有选择器的权值。

上面这个例子,可以看到 h1>b, h2>b 都成功的覆盖了:where >b中的样式,因为:where的样式的权重是0。如果换成is会是什么样?

可以看到,is会使用h1,h2,h3,h4,h5中权重最大的值作为其权值,而他们的权值都一样,所以就会出现上面的样式被下面的样式覆盖掉,所以,h1 > b的样式就会变成红色,而h2 >b的样式变为黄色。让我们看个更明显的例子,给H5加个ID:

这时候,我们给h5加了id="h-five", 那它的权值就是在:is函数列表中最大的,所以:is列表中的所有元素都会使用这个值作为其权值,所以最终h2>b的黄色设定想覆盖红色的CSS就会失败,元素将都显示成红色。