我有一个简单的布局,如果文本不在 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>