Alex Wohlbruck
Alex Wohlbruck

Reputation: 1436

CSS :not selector doesn't work

This is probably a really stupid question, but I can't get the :not selector to work in css. I want to color all text in my page unless it has a class called "nocolor". Here's the code, I don't see the problem:

*:not(.nocolor) {
    color: #f00;
}
<h2>Hello</h2>
<h2 class="nocolor">Hello</h2>

Upvotes: 5

Views: 1980

Answers (3)

Jack Guy
Jack Guy

Reputation: 8523

I was surprised by this behavior but the * selector applies to everything so you have to look out for application to parent elements as well (like body and html tags themselves).

You can fix it by adding body to the selector, like so:

body *:not(.nocolor) {
   color: red;
}

Upvotes: 3

Martin van Driel
Martin van Driel

Reputation: 1837

It's because * is applied to every element including body, which doesn't have the .nocolor class.

Upvotes: 2

Cliff Ribaudo
Cliff Ribaudo

Reputation: 9039

Your selector should be written like so:

:not(.nocolor) {
    color: #f00;
}

Remove the '*', and this will select everything on the page.

See docs here: MDN

Upvotes: 2

Related Questions