Incorporating CSS, my goal is to implement varying styles to the element labeled with the class test
. However, the style should differ based on whether it is situated within an element of class a
or class b
:
<div class="a">
lorem
<div class="b">
ipsum
<div class="test"> </div>
</div>
</div>
It should receive a distinct style compared to
<div class="b">
lorem
<div class="a">
imsum
<div class="test"> </div>
</div>
</div>
However, upon applying the style
.a .test { background-color: red; }
.b .test { background-color: blue; }
both end up with a blue background: https://jsfiddle.net/emk5fozg/4/
I desire the second one to display in red, since it is a more direct child of .a
than .b
.
The issue lies in the fact that utilizing the child selector >
is not viable, as there could potentially be approximately 7 layers of divs in between the pertinent ones. (I have counted them, so please refrain from inquiring about the abundance.)
How can I allocate styles to elements based on their closest ancestor?
To clarify: I strictly intend to style the .test divs themselves, without affecting any surrounding elements. There are numerous other elements preceding and succeeding them that should remain unaffected by the style.