css3:not()选择器在同胞元素上不起作用



我有一个简单的布局,如果文本不在 footer元素中,我想要红色。它可与p标签,a标签等一起使用

但是当我使用footer标签尝试时,它不起作用。

我的代码如下:

p {
  color: #000000;
}
 :not(footer) {
  color: #ff0000;
}
<h1>This is a heading</h1>
<footer>This is a footer.</footer>
<div>This is some text in a div element.</div>
<a href="https://www.w3schools.com" target="_blank">Link to W3Schools!</a>

您需要选择 body的父(否则,根据您的规则,footer将从body继承RED),以便:not(footer)工作。

p的问题是CSS特异性

p {
    color: #000;
}
body > *:not(footer) { /* note that having :not(footer) is the same as *:not(footer), the wildcard is not necessary */
    color: #f00;
}
<h1>This is a heading</h1>
<footer>This is a footer.</footer>
<div>This is some text in a div element.</div>
<p>This is some text in a p element.</p>
<a href="https://www.w3schools.com" target="_blank">Link to W3Schools!</a>

您需要一个父元素才能嵌套以进行:not()选择器,因此在您的代码中 body tag'll作为父元素

工作
body > :not(footer){
  color: #ff0000;
}

这是您的代码:

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

设置所有元素为红色,除了 footer

问题是规则将body元素设置为红色。然后footer继承颜色。

因此,您的规则实际上有效(排除了兄弟姐妹),但是页脚通过继承获得颜色。

代替或针对所有 emblings footer除外),目标所有儿童footer除外)。这消除了继承漏洞:

body > :not(footer) {
    color: #ff0000;
}
<h1>This is a heading</h1>
<footer>This is a footer.</footer>
<div>This is some text in a div element.</div>
<a href="https://www.w3schools.com" target="_blank">Link to W3Schools!</a>

最新更新