我刚刚查找了 :not()
伪类并在那里尝试了示例。有趣的是,它在我的本地计算机上看起来与在 MDN 站点上看起来不同。
比较 jsFiddle和 MDN example .
p:not(.classy) { color: red; }
:not(p) { color: green; }
<p>Some text.</p>
<p class="classy">Some other text.</p>
<span>One more text</span>
输出:
Some text. <-- This is red.
Some other text. <-- This is green?! (It should be black or whatever is the default color)
One more text <-- This is green.
检查元素后,我发现 Some other text
以某种方式从 body
继承了绿色,这受 :not(p)
.
那么为什么 MDN 网站能正确显示它呢?这是一个技巧:
<p style="color: red;">Some text.</p>
<p>Some other text.</p>
<p style="color: green;">One more text</p>
所以我的问题是,如何使用 :not()
正确 并防止继承导致意外结果?
最佳答案
实际上,两者都是正确的。 ;) 在 jsFiddle 中,尝试先定义一个默认颜色,比如
body { color: blue; }
现在,body 没有特殊的颜色设置,所以 :not(p)
也适用于 body,p.classy 继承了 body 的颜色。
参见 http://jsfiddle.net/3Jqxr/1/更新示例。
编辑:由于 :not
选择器的特殊性高于 CSS 中的简单 body
,您实际上必须使用
body:not(p)
对于这个例子。
关于html - 如何使用 CSS :not() properly?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14832738/