:is()、:where()和:has()的用法

1、:is 选择器

is 选择器允许我们同时匹配多个选择器中的一个多个
这意味着可以用更少的代码对同一样式,应用于多个不同的元素上。

1.1 代码示例

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #isContainer :is(h4, h5) {
        color: red;
      }
    </style>
  </head>
  <body>
    <h1>is 选择器</h1>
    <div id="isContainer">
      <h3>h3</h3>
      <h4>h4</h4>
      <h5>h5</h5>
    </div>
  </body>
</html>

这种情况,如若是用传统写法就是

      #isContainer h4,
      #isContainer h5 {
        color: blue;
      }

:is() 括号里面也可以写其他的选择器,不限于此

1.2 兼容性

在这里插入图片描述

2、:where 选择器

:where() 和 :is() 差不多,都可以传入选择器或者匹配规则来简化CSS代码。 主要区别是 where 权重就是0

2.1 代码示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #isContainer :where(h4, h5) {
        color: red;
      }
    </style>
  </head>
  <body>
    <div id="isContainer">
      <h3>h3</h3>
      <h4>h4</h4>
      <h5>h5</h5>
    </div>
  </body>
</html>

在这里插入图片描述

其实他也能实现 is 的效果

      h4,
      h5 {
        color: green;
      }
      :where(h4, h5) {
        color: red;
      }

在这里插入图片描述

如若是这样写的话, 可以看出 ,where 的权重很低

      :is(h4, h5) {
        color: green;
      }

即便是这样写,也可以覆盖掉 where 的样式

2.2 兼容性

在这里插入图片描述

3、:has 选择器

可以理解为 有、包含的 意思

3.1 代码示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #isContainer h3:has(span) {
        color: red;
      }
    </style>
  </head>
  <body>
    <div id="isContainer">
      <h3>h3</h3>
      <h3>
        h4
        <span>h4 的span 你好啊</span>
      </h3>
      <h3>h5</h3>
    </div>
  </body>
</html>

在这里插入图片描述

这个就可以理解为,选中 isContainer 里面,h3 标签中,包含span 元素的 h3

      #isContainer h3:has(span) span {
        color: blue;
      }

在这里插入图片描述

这个可以理解为,选中 isContainer 里面,h3 标签中包含span 元素 的 h3 ,h3 里面的 span 文字颜色改为 blue

      #isContainer h3:has(+ p) {
        color: green;
      }

在这里插入图片描述

这个可以理解为:选中 isContainer 里面,h3 元素,后面紧挨着 p 元素的 h3

:has 用途还是比较多的, 比如之前开发的,列表中,如若这一行的 某一列包含 span 元素并且 span有 data-isExists = ‘1’ 的 那么这一行就加入背景颜色

3.2 兼容性

在这里插入图片描述

参考链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值