I am confused why this example does not 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 expected the first to be red. Here's the JSFiddle.
Interestingly, I found three different ways to make it work:
- Remove top level
<div> from HTML - Change the top level of the
<div> to another 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 the basis, wrap another
<div> around the <section>
According to MDN :
This selector applies to only one element; you cannot use it to exclude all ancestors. For example, body :not(table) a will still apply to links inside the table, since <tr> will correspond to the :not() selector.
That makes sense, but I don't think this is happening here. Since there is nothing between <div class="exclude"> and its direct child <p> , it should run the rule no matter what it is nested inside. What am I missing? I would really appreciate it if someone would help me figure this out.
dom html css css-selectors css3
Jerome Dahdah
source share