Reputation: 15114
I just looked up the :not()
pseudo-class and tried the example there. Interestingly it looks different on my local computer than on the MDN site.
Compare jsFiddle and MDN example.
p:not(.classy) { color: red; }
:not(p) { color: green; }
<p>Some text.</p>
<p class="classy">Some other text.</p>
<span>One more text</span>
The output:
Some text. <-- This is red.
Some other text. <-- This is green?! (It should be black or whatever is the default color)
One more text <-- This is green.
Upon inspecting the element, I found that Some other text
somehow inherits the color green from the body
, which is affected by :not(p)
.
So why is the MDN site showing it correctly? It's a trick:
<p style="color: red;">Some text.</p>
<p>Some other text.</p>
<p style="color: green;">One more text</p>
So my question is, how to use :not()
properly and prevent inheritance from causing unexpected outcomes?
Upvotes: 3
Views: 213
Reputation: 146640
Since you don't set a a default value for <p>
, your <p class="classy">
element inherits from body. You probably want to exclude <body>
from the ruleset:
body :not(p) { color: green; }
Alternatively, you can set a default:
p{ color: black; }
p:not(.classy) { color: red; }
:not(p) { color: green; }
Upvotes: 0
Reputation: 9022
Actually, both are correct. ;) In jsFiddle, try to define a default color first, like
body { color: blue; }
Right now, body has no special color set, so :not(p)
applies to body, too, and p.classy inherits the color from body.
See http://jsfiddle.net/3Jqxr/1/ for updated example.
EDIT: Since the specifity of the :not
selector is higher than a simple body
in CSS, you actually have to set the default color with
body:not(p)
for this example.
Upvotes: 7