Reputation: 15690
I have this DOM:
<div class="a">
<div class="b"></div>
<div class="c"></div>
</div>
I'd like to have this css rule:
.b + .c { margin-left: 220px; }
BUT only within class a
I was hoping that something like this would have worked , but no luck.
.a .b + .a .c {}
Does anyone know if this is possible ?
Upvotes: 3
Views: 368
Reputation: 106483
Use this selector instead:
.a .b + .c {
margin-left: 220px;
}
... or .a > .b + .c
, if you want the rule to be applied only to the children of .a
container, rather than to all its descendants.
Demo.
Now for explanation part. As defined in CSS spec, every selector with +
symbol is treated as selector chain:
A selector consisting of a single simple selector matches any element satisfying its requirements. Prepending a simple selector and combinator to a chain imposes additional matching constraints, so the subjects of a selector are always a subset of the elements matching the last simple selector.
Now that's analyze the expression you've started with:
.a .b + .a .c
According to spec, this is actually treated as...
((.a .b) + .a) .c
In other words, selector is applied...
.c
elements, which....a
elements as their ancestors, which....b
elements as their preceding siblings, which....a
elements as their ancestors.This selector will match .c
element in this HTML:
<div class="a">
<div class="b"></div>
<div class="a">
<div class="c">This is matched</div>
</div>
</div>
In your case, however, you won't have to check for .c
ancestry - it's enough to check for .b
(its preceding sibling) only. If .b
has .a
up its DOM tree, its sibling sure has it too. )
Upvotes: 9