Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 843
leigero Avatar asked Jun 18 '26 02:06

leigero


1 Answers

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>
like image 103
Paulie_D Avatar answered Jun 19 '26 18:06

Paulie_D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!