Proper use of CSS: not a selector to exclude an element when in a specific container

I am developing a series of pages from which I do not control their layout, and this creates some unique problems. The styles are based on the design layout I received, and therefore there are instances - for example, h2 elements that should look different than other specific h2 elements in order for the design to be respected.

I'm currently trying to apply some style that should affect most h2 elements, but not the h2 elements that appear in a div with the class "block". What would the CSS selector look like in this case? I went to a limb and tried it, but I was right in believing that this is not entirely correct.

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

Can someone shed some light? Thank!

+4
source share
2 answers

You can try the following:

h2 {...}

.block h2 {...}
+6
source

I am trying to apply some style that should affect most elements h2, but not h2that appear in a div with a class block.

You did not specify the level at which the h2div exists. So here are a few options if you want to use a pseudo class :not().

If h2- 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>
Run code

If h2- two levels:

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>
Run code

If h2consists of three levels:

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>
Run code

etc.

, :not(), , .

...

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

... , ( ).

: fooobar.com/questions/1650378/...

+2

Source: https://habr.com/ru/post/1655401/


All Articles