【问题标题】:How to properly use the :not selector to solve .b but not .a .b? [duplicate]如何正确使用 :not 选择器来解决 .b 而不是 .a .b? [复制]
【发布时间】:2018-03-15 04:18:38
【问题描述】:

我想定义适用于.b 但不适用于.a .b 的css

不接受以下方式的黑客攻击

.a .b {
   background-color: cornflowerblue;
}

此外,html 可以在任意容器中。 body > .b 也不适用于我的情况

我想使用:not 选择器或不会让我更改.a .b 定义的替代解决方案

div {
  width: 50px;
  height: 50px;
  background-color: cornflowerblue;
  margin: 10px;
  border: 1px solid salmon;
}

.b {
  background-color: green;
}
<div class="a">
  <div class="b"></div>
</div>

<div class="b"></div>

在此处查看代码笔

https://codepen.io/anon/pen/OxOLZE

【问题讨论】:

  • 只是一个旁注,你不想这样做,因为它非常慢(Css 不支持它),只有当你知道 .b 总是直接在一个 . a 已经发布了纯 CSS 的答案

标签: html css css-selectors


【解决方案1】:

这将选择所有不是.a 子元素的.b 元素。

div {
  width: 50px;
  height: 50px;
  background-color: cornflowerblue;
  margin: 10px;
  border: 1px solid salmon;
}

*:not(.a) > .b {
  background-color: green;
}
<div class="a">
  <div class="b"></div>
</div>

<div class="b"></div>

【讨论】:

  • 不,它不会选择 .a > .b。浏览器从右到左读取 CSS,因此这条规则大致翻译为: *:not(.a) > .b 如果有一个类 b 的对象,并且直接在它上面是任何类不是 a 的对象,规则适用 *:not(.a) .b 这将转化为:如果有一个对象具有 b 类,并且在它之上是任何非 a 类的对象,则适用规则,即使在上面有一个对象也适用。 b 没有 .a 作为类
  • 问题要求不是.a .b。答案应该是*:not(.a) .b,以防.b.a 中嵌套得更深?
  • 后代组合器在这种情况下不起作用,因为*:not(.a) 将至少与 html 元素匹配(除非它具有类“a”)所以*:not(.a) .b 将匹配所有具有类的元素“b”,即使有一个具有类“a”的元素是具有类“b”的元素的祖先。要使*:not(.a) .b 起作用,具有类“b”的元素的所有祖先必须具有类“a”。
  • @Elentriel:RTL 评估与此有什么关系?我可以轻松地说“选择任何不是 .a 的元素并找到它的 .b 子元素”,这意味着完全相同。
猜你喜欢
  • 2013-10-07
  • 1970-01-01
  • 2018-11-22
  • 1970-01-01
  • 2021-10-06
  • 2021-08-15
  • 2019-10-27
  • 1970-01-01
  • 2013-11-07
相关资源
最近更新 更多