html - 如何使用 CSS :not() properly?

标签 html css

我刚刚查找了 :not()伪类并在那里尝试了示例。有趣的是,它在我的本地计算机上看起来与在 MDN 站点上看起来不同。

比较 jsFiddleMDN 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/

相关文章:

HTML 表单 - 是否需要名称和 ID?

javascript - 在 Javascript 中创建表

javascript - 点击叠加效果一次触发所有叠加

javascript - 用户向下滚动时的不同导航菜单

css - CSS3 中 transform translateX 的奇怪行为?

javascript - 具有一定 Angular HTML5 Canvas drawImage

javascript - 如何在不加载和 javascript 的情况下向 IE 8 及以下版本显示消息

html - 根据高度水平换行?

html - 段落的一侧边框

CSS 继承问题 - 标记背景位置