非特定 div 元素内的 p 标签否定规则

4
这是我的示例HTML。
<html>
<head>
</head>
<body>
<div>
<p>Text with red color</p>
</div>
<div id="temp">
<div style="margin:0px">
<p>
Text without red color
</p>
</div>
</div>
</body>
</html>

我希望将“color:red”应用于所有不在具有id = temp的“div”内部的“p”元素。
我使用了下面的CSS否定,但没有成功:
p:not(div[id="temp"] p){
color:red;
}
3个回答

3

3
它不会选择位于 div 元素之外的 p 元素。 - MNR
1
正确,但是在提供的代码中,每个 p 都在一个 div 内部。所以我认为这对于这种情况会起作用。 - Thomas
3
如Nasir所说,你的规则不会选择在div元素之外的p元素。我需要一个规则,它应该选择除了位于“具有id temp的div”内部的那个p元素之外的所有p元素。 - Shrinath Shetty
1
是的,现在它很完美,但仅适用于不直接嵌套的“p”子元素。 - MNR
1
谢谢Thomas。你的规则,即:not(#temp) > p { color:red; } 只有在p是id为“temp”的div的直接子元素时才有效。如果p不是直接子元素怎么办?请检查我编辑过的HTML。 - Shrinath Shetty
显示剩余2条评论

2
没有这样的选择器,因为 CSS 中的 :not() 伪选择器只适用于简单的、单元素选择器,如 ID、类、元素或标签名称以及其他相似的选择器。
MDN 中的文档说:
引用: “否定 CSS 伪类 :not(X) 是一个函数符号,它以简单选择器 X 作为参数。它匹配不由参数表示的元素。X 不得包含另一个否定选择器。”

https://developer.mozilla.org/en/docs/Web/CSS/:not

所以我想到的唯一方法是使用具有更高优先级的 CSS 选择器来覆盖你不想选择的元素的样式,这个选择器只匹配你想忽略的元素。
示例链接:http://codepen.io/anon/pen/MyrKKW?editors=1000
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>CSS Selector</title>
  <style>
    p {
      color: red;
    }

    #temp p {
      color: initial;
    }
  </style>
</head>
<body>
  <p>Praesent nonummy mi in odio.</p>
  <div id="temp">
    <p>Inside #temp div: fusce neque. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
    <p>Another p inside #temp div: raesent blandit laoreet nibh. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
  </div>
  <div>
    <p>Inside other div: proin sapien ipsum, porta a, auctor quis, euismod ut, mi. Donec mollis hendrerit risus.</p>
  </div>
</body>
</html>

1

您希望这样做吗?https://jsfiddle.net/Lg0zL3wd/1/

div:not(#temp) p{
color:red;
}

<div id="temp">
  <p>text without red</p>
</div>
<div>
  <p>text with red</p>
  <p>text with red</p>
</div>

谢谢,丹尼什。你的规则不起作用。你的规则不能选择在 div 元素之外的 p 元素。我想要一个规则,应该选择除了“具有 id 为 temp 的 div”中的那个之外的所有 p 元素。 - Shrinath Shetty
在这种情况下,您可以使用普通的CSS而不是:not来实现这一点,就像Nasir建议的那样。 - Danish Adeel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接