基于祖先没有类的CSS选择器

Dom*_*nic 0 html css css-selectors

我想根据祖先不存在的另一个类来设置一个类的样式。

div:not(.evil-class) .element {
  background-color: green;
}
Run Code Online (Sandbox Code Playgroud)
<div class="evil-class">
  <div class="element">An element within the evil class</div>
</div>

<div class="element">An element NOT in the evil class</div>
Run Code Online (Sandbox Code Playgroud)

不确定为什么不起作用?

我知道我可以做相反的事情。对两个元素都应用样式,然后覆盖该样式,但是我不愿意这样做,因为我将覆盖可能在第三方库中更改的样式。

谢谢。

css应用的尽管规则

Que*_*tin 5

div:not(.evil-class) .element意为“与类的东西元素从下降DIV不具有的类恶级

你的元素不是从后裔任何 DIV,所以div:not(.evil-class)不符合任何祖先(而这只是<body>并且<html>在这种情况下)。


当前尚无法在CSS中表达“没有一个祖先有特定的类”。

选择器级别4建议允许:not()包含复杂的选择器,因此将来您可以执行以下操作:

.element:not(div.evil-class *) {
  background-color: green;
}
Run Code Online (Sandbox Code Playgroud)
<div class="evil-class">
  <div class="element">An element within the evil class</div>
</div>

<div class="element">An element NOT in the evil class</div>
Run Code Online (Sandbox Code Playgroud)

目前几乎不存在浏览器支持,但是上面的演示在当前版本的Safari中有效。

  • 浏览器支持率现已达到 90% (2认同)