:where()选择器
以选择器列表作为参数,并选择该列表中任意一个选择器可以选择的元素。:where选择器可以用于简化CSS选择器的编写,并在某些情况下提高CSS选择器的可读性。
使用场景
.class1 span, .class2 span{
font-size: 12px;
}
/* 可简化为 */
:where(.class1 .class2) span {
font-size: 12px;
}
.row1 button,
.row1 a,
.row2 button,
.row2 a{
color: red;
}
/* 可简化为 */
:where(.row1, .row2) :where(button, a){
color:red;
}
优先级
优先级总是0,标签选择器的优先级更高。
.class1 span, .class2 span{
font-size: 12px;
}
:where(.class1 .class2) span {
font-size: 20px;
}
/* 最终字号还是12px */
兼容性
:is() 选择器
作用跟:where()选择器一样,也是以选择器列表作为参数,并选择该列表中任意一个选择器可以选择的元素。区别在于优先级。
:is(ol, ul) ol {
color: chocolate;
}
注意伪元素在 :is() 的选择器列表中无效。
:is(.class1, .class2::before) {
/* 样式无效 */
color: red;
}
:is(.class1, .class2)::before {
/* 样式生效 */
color: red;
}
:is()函数只接受选择器序列作为参数,并且伪元素不是选择器序列之一,只能作为单个选择器中的一部分。所以这段代码会被浏览器忽略掉,其中包含伪元素::before的选择器不会被应用于.class1和.class2元素。正确写法是,将伪元素作为单独的选择器处理。
优先级
:is()的优先级不是0,而是由传入的选择器来决定的。
div {
color: yellow;
}
:where(.test) {
color: pink;
}
<div class="test">where选择器</div>
/* color最终为yellow */
-------------------------------------
:is(.test) {
color: red;
}
div {
color: yellow;
}
<div class="test">is选择器</div>
/* color最终为red,因为类选择器优先级比标签选择器优先级高 */
兼容性
:has()选择器
把可容错相对选择器列表作为参数,提供了一种针对引用元素选择父元素或者先前的兄弟元素的方法。
比如说想要实现:
- 有图片时,div宽高为100*100px
- 没有图片时,div宽高为50*50px
<div class="container">
<img class="test-img" v-if="showImg"></img>
</div>
.container {
width: 50px;
height: 50px;
}
.container:has(img) {
width: 100px;
height: 100px;
}