leigero leigero - 1 month ago 6
HTML Question

CSS not() with attribute selector doesn't seem to work

I have a very simple selector that works, but when adding it to a

:not()
it no longer seems to recognize it.



h2:not([random-attribute~="value"] h2){
color: red;
}
[random-attribute~="value"] h2{
color: blue;
}

<div class="content">
<h2>Same valid selector, not working</h2>
<div random-attribute="value">
<h2>Valid selector turned blue.</h2>
</div>
</div>





From what I understand, if you put a valid selector inside the
not()
you will get any
h2
element that is not whatever is inside the parenthesis. This is intuitive.

What isn't intuitive, is that the selector within the
not()
is valid and works when used alone, but when added to the
not()
it doesn't seem to work.

Is this not a valid way to write this?

Answer

You need to style all h2 element that are descendants of elements that are not [random-attribute~="value"] then style h2 that are.

It doesn't hurt to qualify the selector with a direct child combinator too.

Like so:

*:not([random-attribute~="value"]) > h2 {
  color: red;
}
[random-attribute~="value"] > h2 {
  color: blue;
}
<div class="content">
  <h2>Same valid selector, not working</h2>
  <div random-attribute="value">
    <h2>Valid selector turned blue.</h2>
  </div>
</div>

<h2>some other heading</h2>

Comments