0

Let's say I have this HTML

.A {
  border: thick blue solid;
}

.B {
  border: medium red solid;
}
<div class="root">
  <div class="A">
    <div class="B">
      DON'T SELECT ME
    </div>
  </div>

  <div class="B">
    SELECT ME
  </div>

  <div class="A">
    <div class="C">
      <div class="B">
        ALSO DON'T SELECT ME
      </div>
    </div>
  </div>
</div>

How do I, for example, set the background to yellow of the "SELECT ME" div, without doing so to the other two? I was thinking it should be something like:

.root>:not(.A) .B { background: yellow; }

... but that doesn't seem to work and I don't understand why; and searching the web isn't turning up anything to my shock and surprise. Is this something that can be achieved with CSS?

vicatcu
  • 5,397
  • 5
  • 35
  • 53
  • you would just need to style b and the add the override for b if it is a descendant of a – Pete Oct 23 '20 at 15:44

2 Answers2

1

.A {
  border: thick blue solid;
}

.B {
  border: medium red solid;
}

.root > .B {
  background-color: yellow;
}

.A > .B {
  background-color: green;
}
<div class="root">
  <div class="A">
    <div class="B">
      DON'T SELECT ME
    </div>
  </div>

  <div class="B">
    SELECT ME
  </div>

  <div class="A">
    <div class="C">
      <div class="B">
        ALSO DON'T SELECT ME
      </div>
    </div>
  </div>
</div>

Targeting .B as a direct descendant of .root works:

.root>.B { background: yellow; }

Targeting .B as an direct descendant of .A would allow you to target the .A > .B selectors differently:

.A>.B { background: green; }
Jonny
  • 593
  • 4
  • 15
0

You can use CSS nth-child rule. more details here

.B:nth-child(2) {
   background-color: yellow;
}

.A {
  border: thick blue solid;
}

.B {
  border: medium red solid;
}
.B:nth-child(2) {
   background-color: yellow;
}
<div class="root">
  <div class="A">
    <div class="B">
      DON'T SELECT ME
    </div>
  </div>

  <div class="B">
    SELECT ME
  </div>

  <div class="A">
    <div class="C">
      <div class="B">
        ALSO DON'T SELECT ME
      </div>
    </div>
  </div>
</div>
Nobal Mohan
  • 446
  • 4
  • 19