As an example, if I want Text1 to be red but not Text2:
<div class="red">
Text1
<p class="notred">Text2</p>
</div>
I tried this in css:
.red :not(.notred) {
color: #ff0000;
}
Trying this, it does not apply style to either Text1 or Text2.
As an example, if I want Text1 to be red but not Text2:
<div class="red">
Text1
<p class="notred">Text2</p>
</div>
I tried this in css:
.red :not(.notred) {
color: #ff0000;
}
Trying this, it does not apply style to either Text1 or Text2.
2
Answers
CSS selectors must target an element (with some few exceptions like
::first-line
pseudoelement).Text1
is not an element, so (again, ignoring::first-line
) you cannot target it with a single rule. As @JHeth says, use two rules: one to set the red for.red
, and another to cancel it in.notred
.Of course, if you are sure
Text1
will fit in one line, you can cheat, but it is a very specific solution for a very specific situation:To explain why your CSS selector
.red :not(.notred)
doesn’t work, it targets a descendant element of.red
which is not.notred
..red
has only one descendant element (remember,Text1
is a text node, which is not an element!), and it is.notred
— so the rule doesn’t apply to anything. Here would be an example where your CSS selector would apply:Here,
<p>Text1</p>
is an element, is not.notred
, and is a descendant of a.red
element, so it can be found by your selector.You can achieve it like this.