【问题标题】:Why is :not(p) seemingly selecting <p> tags?为什么 :not(p) 似乎选择了 <p> 标签?
【发布时间】:2013-04-16 15:08:49
【问题描述】:

我的 HTML 是这样的:

<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="stylesheet.css">
<head>
</head>
<body>
<p>hiya</p>
<h1>this is h1</h1>
<h2>this is h2</h2>
</body>
</html>

我的 stylsheet.css 是这样的:

:not(p)
{
color:#ff0000;
} 

然而一切都是红色的,包括&lt;p&gt;。我尝试过 Firefox 20、Internet Explorer 10 和 Chrome。它似乎没有比这更基本的了,但我不知道为什么这不起作用(即防止&lt;p&gt; 变红)。对此的任何帮助将不胜感激。

【问题讨论】:

  • 我认为,在 css 中,你在 stylesheet.css 中使用 body { color: red }

标签: html css css-selectors


【解决方案1】:

:not(p) 匹配 body

默认的color 值为inherit

p 没有设置样式。

p 因此从body 继承其颜色,即红色。

解决方案:明确定义您想要的红色,或者为p 明确设置不同的颜色(即不要使用:not),或者使用:not(body):not(p)

【讨论】:

  • 注意,在真正的 CSS OP 中可能需要将选择器放松为 :not(body) :not(p)
  • :not(body):not(p) 不起作用(在 Chrome 上):jsfiddle.net/jBjZ2 因为 Chrome 认为 &lt;html&gt; 也可以有样式,元素也可以继承它。
  • @Passerby :not(html):not(body):not(p),自然而然。
  • 那么为什么不body :not(p)?在我看来,这会跳过htmlbody
  • 一个很好的答案,但在“默认 color 值是 inherit”中有一个术语不准确。 color 的初始值由规范“取决于用户代理”,通常没有浏览器默认值,body 除外。这意味着在这种情况下,bodyp 子级继承了值 red - 但因为这些元素在任何样式表中都没有设置 color
【解决方案2】:

这看起来是因为您没有为 p 标签定义特定的样式。所以 :not(p) 甚至适用于 body 元素并继承。

【讨论】:

    【解决方案3】:

    你可以为&lt;p&gt;创建一个单独的id,你可以在css中使用not

    HTML

    <p class="hiya" id="hiya">hiya</p>
    <p class="hi" id="hi">hi</p>
    <h1>this is h1</h1>
    <h2>this is h2</h2>
    

    CSS

    p:not(#hiya) { color:#ff0000; }

    这将为&lt;p&gt; 生成红色输出,但ID 为“hiya”的&lt;p&gt; 除外。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-14
      • 2014-11-02
      • 1970-01-01
      • 2021-05-01
      • 2012-01-13
      • 1970-01-01
      相关资源
      最近更新 更多