I'm confused as to why this example doesn't work:
CSS:
p {
color: red;
}
div:not(.exclude) p {
color: green;
}
HTML:
<div>
<div class="exclude">
<p>I should be red</p>
</div>
<div>
<p>I should be green</p>
</div>
</div>
The end result is that both <p>
are green, but I would have expected the first one to be red. Here's a JSFiddle.
Interestingly, I found three different ways to make it work:
- Remove the top-level
<div>
from the HTML - Change the top-level
<div>
to a different element (e.g.<section>
) - Add an extra
div
to the beginning of the second CSS selector (div div:not(.exclude) p
)
And another weird way to break it:
- Using solution 2 as a basis, wrap another
<div>
around the<section>
This selector only applies to one element; you cannot use it to exclude all ancestors. For instance,
body :not(table) a
will still apply to links inside of a table, since<tr>
will match with the:not()
part of the selector.
That makes sense, but I don't think that this is happening here. Since there is nothing between <div class="exclude">
and its direct child <p>
, it should trigger the rule regardless of what it is nested inside. What am I missing? I'd really appreciate if someone could help me understand this.
` is turned green before it even reaches `