基于祖先没有类的CSS选择器 [英] CSS selector based on ancestors not having a class

查看:63
本文介绍了基于祖先没有类的CSS选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to style a class based on another class not existing in the ancestors.

div:not(.evil-class) .element {
  background-color: green;
}

<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>

不确定为什么不起作用吗?

Not sure why that doesn't work?

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

I'm aware I can do the inverse; apply a style to both elements and then overwrite that style, but I'd rather not do that as I'd be overwriting styling which could change in a third party lib.

谢谢.

推荐答案

div:not(.evil-class).element 的意思是类 element 的后代,该 div 不具有类 evil-class "

div:not(.evil-class) .element means "Something with the class element that is descended from a div which does not have the class evil-class"

您的元素不是 any div的后代,因此 div:not(.evil-class)与任何祖先都不匹配(它们仅是< body> < html> ).

Your element is not descended from any div, so div:not(.evil-class) doesn't match any of the ancestors (which are only <body> and <html> in this case).

目前尚无办法在CSS中表达没有一个祖先有特定的类别".

There is currently no way to express "None of the ancestors have a specific class" in CSS.

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

Selectors Level 4 proposes allowing :not() to contain complex selectors so in the future you may be able to do something like:

.element:not(div.evil-class *) {
  background-color: green;
}

<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>

浏览器支持当前为几乎不存在,但该演示以上功能适用于当前版本的Safari.

Browser support is currently almost non-existent, but the demo above works in current versions of Safari.

这篇关于基于祖先没有类的CSS选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆