Reputation: 2603
Using css, I want to apply different styles to the element with the class test
. But the style should be different, if it is inside an element with class a
or class b
:
<div class="a">
lorem
<div class="b">
ipsum
<div class="test"> </div>
</div>
</div>
Should get a different style then
<div class="b">
lorem
<div class="a">
imsum
<div class="test"> </div>
</div>
</div>
But if I apply the style
.a .test { background-color: red; }
.b .test { background-color: blue; }
both will have blue background: https://jsfiddle.net/emk5fozg/4/
I want the second one to be red, because it is a more direct child of .a
than .b
.
The problem is, I can not use the child selector >
, because there may be some 7 or so layers of divs in between the relevant ones. (I counted, please don't ask why so many.)
How can I assign styles to elements based on most recent ancestor?
To clarify: I only want to style the .test divs, nothing around them. There are lots of other elements before and after them that should not get a style.
Upvotes: 2
Views: 106
Reputation: 394
The easiest way is too specify the entire filiation:
.b .a .test { background-color: red; }
.a .b .test { background-color: blue; }
and even more precise by specifying the direct parents:
.b > .a > .test { background-color: red; }
.a > .b > .test { background-color: blue; }
Upvotes: 0
Reputation:
They are the same. Is just like if you write first
.test {
background-color:red;
}
and then change it to blue.You will have red color just if you write like this
.b .test { background-color: blue; }
.a .test { background-color: red; }
Upvotes: 1
Reputation: 6476
You could do it like this:
.a .test, .b .a .test{ background-color: red; }
.b .test, .a .b .test { background-color: blue; }
<div class="a">
<div class="b">
<div class="test"> </div>
</div>
</div>
<div class="b">
<div class="a">
<div class="test"> </div>
</div>
</div>
Upvotes: 2
Reputation: 1199
you could do it like that, just add one more selector
https://jsfiddle.net/emk5fozg/2/
.a .b .test {
background-color: blue;
}
.b .a .test {
background-color: red;
}
Upvotes: 3