user4671351
user4671351

Reputation:

Correct use of CSS :not selector for excluding element when in particular container

I am styling a series of pages of which I have no control of their markup, and it is presenting some unique challenges. The styles are based on a design mockup that I was given and therefore there are instances of- for example- h2 elements that must look different than other particular h2 elements in order for the design to be adhered to.

Currently, I am trying to apply some styling that should affect most h2 elements, but not h2 elements which appear within a div with the class "block". How would the CSS selector look in this case? I went out on a limb and tried this, but was correct in assuming it wasn't quite right.

h2:not(.block h2) {
   ~styling for main h2 elements~
}
.block h2 {
  ~separate styling for h2 elements within .block div~
}

Can someone shed some light? Thanks!

Upvotes: 4

Views: 1905

Answers (2)

Michael Benjamin
Michael Benjamin

Reputation: 371261

I am trying to apply some styling that should affect most h2 elements, but not h2 elements which appear within a div with the class block.

You haven't indicated the level where the h2 exists within the div. So here are a few options, if you want to use the :not() pseudo-class.

If the h2 is one level in:

div:not(.block) h2 {
    color: red;
}
<div class="block">
    <h2>with block class</h2>
</div>

<div>
    <h2>without block class</h2>
</div>

If the h2 is two levels in:

div:not(.block) div h2 {
  color: red;
}
<div class="block">
  <div>
    <h2>with block class</h2>
  </div>
</div>

<div>
  <div>
    <h2>without block class</h2>
  </div>
</div>

If the h2 is three levels in:

div:not(.block) div div h2 {
  color: red;
}
<div class="block">
  <div>
    <div>
      <h2>with block class</h2>
    </div>
  </div>
</div>

<div>
  <div>
    <div>
      <h2>without block class</h2>
    </div>
  </div>
</div>

and so on...

Also keep in mind that :not(), as it currently exists in most browsers, only accepts simple selectors as an argument.

Your example...

h2:not(.block h2) {
   ~styling for main h2 elements~
}

... will fail in most browsers because the argument contains a complex selector (created by a descendant combinator, in this case).

More details here: https://stackoverflow.com/a/37305971/3597276

Upvotes: 1

You can try this:

h2 {...}

.block h2 {...}

Upvotes: 5

Related Questions