skip to Main Content

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


  1. 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.

    .red { color: red; }
    .notred { color: black; }
    <div class="red">
      Text1
      <p class="notred">Text2</p>
    </div>

    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:

    .red::first-line { color: red; }
    <div class="red">
      Text1
      <p class="notred">Text2</p>
    </div>

    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:

    .red :not(.notred) { color: red; }
    <div class="red">
      <p>Text1</p>
      <p class="notred">Text2</p>
    </div>

    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.

    Login or Signup to reply.
  2. .red {
      color: #ff0000;
    }
    
    .notred {
      color: #000000;
    }
    <div class="red">
      Text1
      <p class="notred">Text2</p>
    </div>

    You can achieve it like this.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search