所以我有一个带有class='content'
的div,在其中,还有一个具有属性style='background-color:#FF0000'
的div,所以我的代码如下:
<div class='content'>
Here is some text outside the red background div
<div style='background-color:#FF0000'>
Here is some text inside the red background div
</div>
</div>
在我的样式表中,我有以下内容:
[style^='background'] {
color:#00FF00
}
这可行,我在红色背景内得到绿色文本。但是:
:not([style^='background']) {
color:#00FF00
}
此静止使红色背景文本以及文档中的所有其他内容变为绿色。我尝试了以下方法:
div:not([style^='background']) {
color:#00FF00
}
.content :not([style^='background']) {
color:#00FF00
}
:not([style]) {
color:#00FF00
}
当显然我拥有:not
选择器时,所有这些都会使红色背景文本变为绿色。
但是,我在其他地方:
.content div:not([style^='text-align']) {
color:#1f1f1f;
}
.content div :not(span[style^='font-size: 150%']) {
color:#EEE;
}
这些工作正常。
所以我不明白为什么红色背景div根本无法工作,并被:not
选择器选中了?
示例:
:not(.content) {
color:#FF0000
}
<div class='content'>
Here is some text that shouldn't be red
</div>
答案 0 :(得分:2)
color
是inherited property。因此,如果您的元素未设置颜色,则它将从下一个定义了颜色的祖先元素继承颜色。在您的示例中,
:not(.content) { color: #F00; }
这也以body
元素为目标,因此您的div.content
继承了color: #F00;
。
为避免这种情况,请在不需要继承的元素上指定继承的属性。
.content { color: green; }
:not(.content) {
color: red;
}
<div class="content">
Here is some text that shouldn't be red
</div>
答案 1 :(得分:0)
Quirks, tricks, and unexpected results of :not
:not(.foo)
将匹配.foo
以外的任何内容,包括<html>
和<body>
。
您需要增加特异性来避免这种情况,例如div:not(.content)
。
此外:
div:not([style^='background']) {
/* also targets parent divs */
color: #00FF00;
}
.content :not([style^='background']) {
/* You have a space here - this targets _children_ of .content
that are :not([style^='background']. Is this what you want? */
color: #00FF00;
}
请记住,“ CSS”中的“ C”代表层叠,其中一个方面是继承的样式。许多样式(例如color
)也会影响匹配元素的子元素,而不仅仅是元素本身。