3

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>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
sjw0525
  • 329
  • 2
  • 17

3 Answers3

2

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>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
2

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>
dippas
  • 58,591
  • 15
  • 114
  • 126
2

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;
}
satyajit rout
  • 1,623
  • 10
  • 20
  • What if I have h3 tags outside of the footer and one inside of the footer. How would I say I want all h3 tags except the h3 tag in the footer to have a certain styling? – sjw0525 Nov 30 '17 at 16:33
  • add class to footer inside footer and write this h3:not(.css){color: red;}...see this pen u'll understand (https://codepen.io/satyajit11/pen/XzoWeB) – satyajit rout Nov 30 '17 at 17:43
  • I can't do it without adding a class? and using :not(footer) instead of class name? – sjw0525 Nov 30 '17 at 17:51