Q:

Let rule with closest bounding class win in CSS

I have the following scenario in HTML:
<div class="red">
     <div class="blue">
         ... <-- maybe more nested parents
             <div class="x">Test</div>
     </div>
</div>

Given the following CSS:
.blue.x, .blue .x {
  background: blue;
}
.red.x, .red .x {
  background: red;
}

In this case the background of the x element will obviously be red, because both rules (actually it are 4, but only .red.x and .blue.x would apply in this example) apply, and the red background was the last rule defined.
But how would i write a rule, so that the inner "blue" class (which is the closer parent to x) would be chosen instead? I want to switch the color depending on the structure of the classes, and not on the order in the CSS file.

A:

Based on the HTML you provided, you could use the direct child selector, >, in order to select the .x element that is a direct child (rather than a descendant).

.blue.x,
.blue > .x {
  background: blue;
}
.red.x,
.red > .x {
  background: red;
}
<div class="red">
  <div class="blue">
    <div class="x">Blue</div>
  </div>
</div>
  
<div class="blue">
  <div class="red">
    <div class="x">Blue</div>
  </div>
</div>

However, since only the direct .x child element is selected, it's worth pointing out that won't work if the .x element is nested deeper. But you can work around this to a certain degree:

.blue.x,
.blue > .x,
.blue > * > .x {
  background: blue;
}
.red.x,
.red > .x,
.red > * > .x {
  background: red;
}
<div class="red">
  <div class="blue">
    <div>
      <div class="x">Blue</div>
    </div>
  </div>
</div>
  
<div class="blue">
  <div class="red">
    <div>
      <div class="x">Red</div>
    </div>
  </div>
</div>

Alternatively, if the solutions above aren't flexible enough, then you could also force the element to inherit the closest parent's value:

.blue,
.blue.x {
  background: blue;
}
.blue * .x {
  background: inherit;
}
.red,
.red.x {
  background: red;
}
.red * .x {
  background: inherit;
}
<div class="red">
  <div class="blue">
    <div>
      <div class="x">Blue</div>
    </div>
  </div>
</div>

<div class="blue">
  <div class="red">
    <section>
      <div>
        <div>
          <div>
            <div class="x">Red</div>
          </div>
        </div>
      </div>
    </section>
  </div>
</div>

