1

This is a pretty simple question that I can't quite get my head around.

I have a series of divs like this:

<h1>Heading 1</h1>

<h2>Heading 2</h2>

<p>Paragraph text</p>

<h2>Heading 3</h2>

<p>Paragraph text</p>

In CSS I can target h2 tags that follow from h1 tags with: h1+h2{}, however I can't seem to use :not() in this way. For example, I'd like to use:

#text h2:not(h1+h2){
    margin-top:3em;
}

But this doesn't seem to work. Am I doing some sort of stupid syntax error or is this not possible to do?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
JVG
  • 20,198
  • 47
  • 132
  • 210

2 Answers2

5

As mentioned previously, the CSS :not() selector doesn't allow combinators inside it, so indeed, it's a syntax error.

In this case, because of the way the + combinator works, you should be able to simply move + h2 out of the :not() and remove the h2 before it, like so:

#text :not(h1) + h2 {
    margin-top: 3em;
}

In case h2 will ever be the first child (which, given your sample, it shouldn't be), and you want to match that, you need to extend the selector a bit:

#text h2:first-child, #text :not(h1) + h2 {
    margin-top: 3em;
}

Failing either of those two methods, however, you can always use the good ol' override, as Joseph Silber demonstrates.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • @Joseph Silber: That's not necessary. It's a good alternative! :) – BoltClock Jan 14 '13 at 04:09
  • @Joseph Silber: I should probably make it a point to do that with all my answers since I'm not happy with how the highlighting works either. Thanks for the reminder. – BoltClock Jan 14 '13 at 04:20
  • @Jascination: Glad I helped. You may want to look at my answer to your previous question if you haven't already :) – BoltClock Jan 14 '13 at 05:50
3

The CSS not pseudo selector does not allow complex selectors. There's nothing you can do about it.

To get the functionality you want, you'll have to override it:

#text h2 {
    margin-top:3em;
}

#text h1 + h2 {
    margin-top: 0;
}
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • Ah ok. Yeah that's what I currently have done, I thought a more elegant solution would be to condense it into 1 rule instead of 2 but guess it can't be done. – JVG Jan 14 '13 at 04:00