尼采般地抒情

尼采般地抒情

尼采般地抒情

音乐盒

站点信息

文章总数目: 316
已运行时间: 1570

前言: 本文记录一下CSS3中逻辑选择器中的has和not, has相当于根据子代条件来选择父代, not类似过滤条件. 使用前先检查代码运行的浏览器环境是否符合如下截图条件.

not

对当前节点的过滤筛选

<html>
  <head>
    <title>css</title>
    <style>
      div.parent:not(.not-parent) {
        border: 1px red solid;
      }
    </style>
  </head>
  <body>
    <div class="parent not-parent">0000</div>
    <div class="parent">
      <div>1111</div>
      <div>
        <div class="active">2222</div>
      </div>
    </div>
    <div class="parent">
      <div>3333</div>
      <div>4444</div>
    </div>
    <p></p>
  </body>
</html>

has

has选择器: 根据子是否符合条件来选择父级

设置子代中有active类的parent类名div的样式

<html>
  <head>
    <title>css</title>
    <style>
      div.parent:has(.active) {
        border: 1px red solid;
      }
    </style>
  </head>
  <body>
    <div class="parent">
      <div>1111</div>
      <div>
        <div class="active">2222</div>
      </div>
    </div>
    <div class="parent">
      <div>3333</div>
      <div>4444</div>
    </div>
    <p></p>
  </body>
</html>

如果将上面css改为, 边框则消失

div.parent:has(> .active) {
  border: 1px red solid;
}

还可以表示兄弟跟随关系

div.parent:has(+ p) {
  border: 1px red solid;
}

和not搭配使用, 如下表示不包含active后代的div.parent的标签

div.parent:not(:has(.active)) {
  border: 1px red solid;
}

上述not和has位置互换表示的意思不一样

div.parent:has(:not(.active)) {
  border: 1px red solid;
}

和表单一些元素搭配使用

<html>
  <head>
    <title>css</title>
    <style>
      div:has(input:focus) {
        border: 1px red solid;
      }
    </style>
  </head>
  <body>
    <div>
      <input type="text" value="111" />
    </div>
    <div>
      <input type="text" value="222" />
    </div>
  </body>
</html>


一些常规使用CSS选择器可以参考另一篇文章: CSS/CSS3选择器总结 | 尼采般地抒情

评论区