3

Here is the html layout

<div class="wrap">
    <div class="section">
        <span class="text">text1</span>
    </div>
    <span class="text">text2</span>
<span class="not-text">don't color me!</span>
</div>

Im trying to give a style to all "text" spans which are not in the "section" divs. I tried this, but it doesn't seem to be working

.wrap :not(.section) .text 

fiddle

Any help is greatly appreciated!

Edit: There are several workarounds for this case including the use of > operator like in ".wrap > .text", but I would like to know how to make the :not selector working, to make use of it in the future

Community
  • 1
  • 1
skyisred
  • 6,855
  • 6
  • 37
  • 54

3 Answers3

5

When you use .wrap :not(.section) .text, this is what you're telling the browser:

  1. Look for an element with a class of .text
  2. which lives inside an element that does not have a class of .section
  3. which lives inside an element that has a class of .wrap

If you look closely at your markup, none of your elements meet that selector criteria.

In the markup you provided, I don't think you can specifically select those .text elements that are not descendants of .section using :not().

The closest you could get is by using a direct descendant selector, like this:

.wrap > .text

You could also select and style all .text descendants of .wrap (whether direct or not), and then cancel those styles for any .text elements inside of .section, like this:

.wrap .text {
  // your styles here
}

.wrap .section .text {
  // your cancelled styles here
}
zxqx
  • 5,115
  • 2
  • 20
  • 28
  • This is how I break down complex selectors in my own answers as well. A different explanation of pretty much the same situation can be found [here](http://stackoverflow.com/questions/7084112/css-negation-pseudo-class-not-for-parent-ancestor-elements/7084147#7084147). In short, using `:not()` with descendant selectors is unreliable. – BoltClock Feb 15 '13 at 07:41
1

You can probably use:

.wrap > span
.wrap > *:not(div)
.wrap > *:not(.section)
James Coyle
  • 9,922
  • 1
  • 40
  • 48
  • I meant them as separate things, not all at once. They would all do the same thing with the provided HTML code. – James Coyle Feb 14 '13 at 23:31
0

Best option given the constraints of CSS are to write a rule for all text and then override them back to the previous value for those within .section. So

.wrap .text {
   // the styles you want
}

.wrap .section .text {
  // styles undoing the styles above... depending on what the styles are it may not always be possible

}
wheresrhys
  • 22,558
  • 19
  • 94
  • 162