destiny destiny - 1 month ago 9
CSS Question

CSS :not() selector affects other elements, what am I missing?

I have the following test code:

<html>
<head>
<style type="text/css">
#test, .random-class { font-weight:bold; }
#test, .random-class:not('.another-class') { color:red; }
</style>
</head>
<body>
<div id="test">hello world</div>
</body>
</html>


This produces the following output:

enter image description here

In my understanding, hello world should be bold and red, but it's only bold.
I expected the second rule to affect


  • the element with id test OR

  • any element with class .random-class and not class .another-class



What am I missing here? Why is the second rule not applied?

Answer

You don't need the quotes around the class in your :not() selector, if you change it so it becomes:

#test, .random-class:not(.another-class) 
{ 
    color:red; 
}

It will work as you expect it to

Take a look here for a demo

Take a look here for the docs on the :not() selector

Mentioned by @KWeiss in the comments:

Specifically the quotes are making the selector invalid so the rule is not applied

Hope this helps!