3

Consider the following HTML:

<div class="a">
    <div class="b">Hello</div>
  </div>
  <div class="c">
    <div class="b">World</div>
</div>

Adding the following CSS colors only "World" in red, as expected:

.c .b {
  color: red;
}

But, adding the following CSS instead colors both "Hello" and "World" in red:

:not(.a) .b {
  color: red;
}

Why?

1

2 Answers 2

7

You need to give it like this:-

Demo

div:not(.a) .b {
  color: red;
}

Pseudo-class :not

Syntax is selector:not(){ properties }

Sign up to request clarification or add additional context in comments.

5 Comments

The syntax does not actually require the :not() to be qualified by anything, but it's good practice anyway.
Thanks @BoltClock but looking at the syntax and examples in the documentation and trying without :not(.a) .b it did not make the appropriate selection atleast in Chrome. I have also used it this way myself.. Probably i am missing something.. :|
Yep, what I'm basically saying is that it works without the "selector" part but like you mentioned it doesn't do what you expect. Also see my comment link on the question.
@Mr Lister: Hm? They do handle both of them equivalently and according to spec...
@BoltClock Sorry, I had trouble looking beyond these answers, which turned out to be incorrect after all.
3

Since the :not pseudo-class represents an element that is not represented by its argument, you have to specify the element you want to exclude before the :not selector

Per your example, try this instead:

div:not(.a) .b {
  color: red;
}

1 Comment

No... the argument is what's inside the parentheses - in this case it's .a, which you are excluding, not div, which is what you want to limit the selector to. Also see my comment on PSL's answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.