Doodles
Doodles

Reputation: 57

CSS :not wont work as expected

I want to select elements that doesn't have both .test and .test1 classes. The following won't work.

ul li:not(.test.test1)
{
    color:red;
}
<ul>
    <li class="test test1">one..</li>
    <li class="two">two</li>
    <li class="three">three</li>
</ul>

Upvotes: 1

Views: 89

Answers (3)

Rounin
Rounin

Reputation: 29453

Quite often, whenever you find yourself in a situation where you need to use :not, there will be a more elegant way to re-write your styles, deploying positive rather than negative targeting.

For instance, rather than targeting everything which isn't .test.test1 and giving it color:rgb(255,0,0), why not:

  • Color everything color:rgb(255,0,0); and then
  • Positively target .test.test1, re-coloring it color:rgb(0,0,0)

That way you take advantage of the cascade, in exactly the way that it is supposed to work.

li {
color: rgb(255,0,0);
}

li.test.test1 {
color: rgb(0,0,0);
}
<ul>
    <li class="test test1">one..</li>
    <li class="two">two</li>
    <li class="three">three</li>
</ul>

Upvotes: 4

Paulie_D
Paulie_D

Reputation: 114981

This is expected as per MDN

"The negation CSS pseudo-class, :not(X), is a functional notation taking a simple selector X as an argument."

Unfortunately yours in not a simple selector.

The CSS Spec definition of a simple selector is:

...an element matched by a particular aspect. A type selector, universal selector, attribute selector, class selector, ID selector, or pseudo-class is a simple selector.

Unfortunately, your is a compound selector as it has two classes.

@Rounin has the optimal solution here. The above is just explanation as to why your selector fails.

Upvotes: 3

KanUXD
KanUXD

Reputation: 707

This should work :

ul li:not(.test),ul li:not(.test1)
{
    color:red;
}

Upvotes: 1

Related Questions