在 CSS 中,您提到的符号是:
-
> 是子组合子;
-
+ 是相邻的兄弟组合;
-
~ 是通用兄弟组合子。
它们之间的区别是这样的:
#store > .shoppingCart { background-color: red; }
<div class=shoppingCart>This will not be targeted</div>
<div id=store>
<div class=shoppingCart>This WILL be targeted</div>
<div class=shoppingCart>This WILL ALSO be targeted</div>
<div class=inner>
<div class=shoppingCart>This will not be targeted</div>
</div>
</div>
<div class=shoppingCart>This will not be targeted either</div>
<div class=shoppingCart>Neither will this</div>
> 组合器仅选择指定选择器的直接子元素(直接位于第一个下方的元素),因此在这种情况下,仅选择紧接在 #store 下方的子元素。
#store + .shoppingCart { background-color: red; }
<div class=shoppingCart>This will not be targeted</div>
<div id=store>
<div class=shoppingCart>This will not be targeted</div>
<div class=shoppingCart>This will not be targeted either</div>
<div class=inner>
<div class=shoppingCart>This will not be targeted either</div>
</div>
</div>
<div class=shoppingCart>This WILL be targeted</div>
<div class=shoppingCart>But this one won't be</div>
+ 组合器选择一个元素,它是第一个元素的直接下一个兄弟元素(位于同一级别的元素,即彼此相邻的元素),因此如果有一个 .shoppingCart 是兄弟元素在#store 之后,它将被选中——但前提是该元素在第一个元素之后;不能以这种方式选择上一个兄弟。
#store ~ .shoppingCart { background-color: red; }
<div class=shoppingCart>This will not be targeted</div>
<div id=store>
<div class=shoppingCart>This will not be targeted</div>
<div class=shoppingCart>This will not be targeted either</div>
<div class=inner>
<div class=shoppingCart>This will not be targeted either</div>
</div>
</div>
<div class=shoppingCart>This WILL be targeted</div>
<div class=shoppingCart>This WILL be targeted as well</div>
~ 组合器选择一个元素,它是第一个元素的任何后续同级元素,因此如果有一个 .shoppingCart 作为 #store 的同级跟随,它将被选中。