CSS3 :not() selector not working on sibling element

Question

I have a simple layout where I want the text red if it is not in the footer element. It works with p tags, a tags etc.

But when I try it with footer tag it doesn't work.

My code is below:

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>


Show source
| html   | css   | html5   | css3   | css-selectors   2017-11-29 20:11 3 Answers

Answers to CSS3 :not() selector not working on sibling element ( 3 )

  1. 2017-11-29 20:11

    This is your code:

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

    That sets all elements to red, except the footer.

    The problem is that the rule sets the body element to red. Then the footer inherits the color.

    So your rule actually works (the sibling is excluded), but the footer gets the color nonetheless through inheritance.

    Instead or targeting all siblings (except footer), target all children (except footer). This eliminates the inheritance loophole:

    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. 2017-11-29 20:11

    You need to select the parent which is body (otherwise footer will inherit red from body as per your rule stated), in order for :not(footer) to work.

    Regards to p its a matter of CSS 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. 2017-11-30 08:11

    you need a parent element to nested for :not() selector to work so here in your code body tag'll work as parent element

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

Leave a reply to - CSS3 :not() selector not working on sibling element

◀ Go back