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:
<div>
from the HTML<div>
to a different element (e.g. <section>
)div
to the beginning of the second CSS selector (div div:not(.exclude) p
)And another weird way to break it:
<div>
around the <section>
According to MDN:
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.
:not() The :not() CSS pseudo-class represents elements that do not match a list of selectors. Since it prevents specific items from being selected, it is known as the negation pseudo-class.
A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s). For example, :hover can be used to change a button's color when the user's pointer hovers over it.
If you're talking about pseudo-classes, then yes, you can combine them in any order.
The cascade is an algorithm that defines how user agents combine property values originating from different sources. The cascade defines the origin and layer that takes precedence when declarations in more than one origin or cascade layer set a value for a property on an element.
You have an overriding <div>
even higher than <div class="exclude">
.
In your styles, you have indicated that - as far as the :not
pseudo-class is concerned - any ancestor <div>
will do. (ie. a grandparent <div>
is just as good as a parent <div>
.)
To focus on the immediate parent, your CSS needs to employ the direct child selector (>
):
p {
color: red;
}
div:not(.exclude) > p {
color: green;
}
<div>
<div class="exclude">
<p>I should be red</p>
</div>
<div>
<p>I should be green</p>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With