【问题标题】:CSS3 :not() selector not working on sibling elementCSS3:not()选择器不适用于兄弟元素
【发布时间】:2018-05-13 14:21:45
【问题描述】:

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

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    这是你的代码:

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

    这会将 所有 元素设置为红色,footer 除外。

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

    所以你的规则确实有效(兄弟姐妹被排除在外),但页脚仍然通过继承获得颜色。

    改为定位所有兄弟姐妹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>

    【讨论】:

      【解决方案2】:

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

      关于pCSS specificity 的问题

      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>

      【讨论】:

        【解决方案3】:

        你需要一个父元素来嵌套 :not() 选择器才能工作,所以在你的代码中 body 标签将作为父元素工作

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

        【讨论】:

        • 如果我在页脚外有一个 h3 标签,而在页脚内有一个标签怎么办。我怎么说我希望除了页脚中的 h3 标签之外的所有 h3 标签都具有某种样式?
        • 在页脚内添加类到页脚并写下这个 h3:not(.css){color: red;}...看看这支笔你就会明白 (codepen.io/satyajit11/pen/XzoWeB)
        • 不加类就不行了?并使用 :not(footer) 而不是类名?
        猜你喜欢
        • 2021-11-22
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-13
        相关资源
        最近更新 更多