多条件选择时会用到的CSS伪类选择器

: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;
}

 兼容性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值