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?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746
  • Using `:not()` to exclude parent elements is not reliable - see http://stackoverflow.com/questions/7084112/css-negation-pseudo-class-not-for-parent-ancestor-elements/7084147#7084147 – BoltClock May 07 '13 at 19:59

2 Answers2

7

You need to give it like this:-

Demo

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

Pseudo-class :not

Syntax is selector:not(){ properties }

PSL
  • 123,204
  • 21
  • 253
  • 243
  • 1
    The syntax does not actually *require* the `:not()` to be qualified by anything, but it's good practice anyway. – BoltClock May 07 '13 at 19:56
  • 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.. :| – PSL May 07 '13 at 20:13
  • 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. – BoltClock May 07 '13 at 20:17
  • @Mr Lister: Hm? They do handle both of them equivalently and according to spec... – BoltClock May 08 '13 at 07:48
  • @BoltClock Sorry, I had trouble looking beyond these answers, which turned out to be incorrect after all. – Mr Lister May 08 '13 at 08:16
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;
}
Lior Elrom
  • 19,660
  • 16
  • 80
  • 92
  • 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. – BoltClock May 07 '13 at 19:57