相邻的CSS选择器(+)无法正常工作

时间:2016-06-24 15:34:02

标签: html css

我遇到了“加”CSS选择器的问题,它应该针对直接的兄弟姐妹,但是由于一些莫名其妙的原因它无法正常工作。这是一个错误,或者我不明白它应该如何工作。

元素B,C和D都应该是红色的 - 但它们仍然是素瓷。

span {
	display: block;
	background-color: bisque;
}
.outside + .outside {
	background-color: red !important;
}
<span class="outside">
	<span class="inside">A</span>
</span>
<span class="outside">
	<span class="inside">B</span>
</span>
<span class="outside">
	<span class="inside">C</span>
</span>
<span class="outside">
	<span class="inside">D</span>
</span>

我也尝试了一些变体 - 即span.outside + span.outside span.outside + *.outside ~ .outside - 但它们似乎都没有效果。如果删除bisque声明,元素只会变为红色。

1 个答案:

答案 0 :(得分:2)

您应该使用background-color: bisque上的outside而不是span

&#13;
&#13;
.outside {
  display: block;
  background-color: bisque;
}
.outside + .outside {
  background-color: red;
}
&#13;
<span class="outside">
	<span class="inside">A</span>
</span>
<span class="outside">
	<span class="inside">B</span>
</span>
<span class="outside">
	<span class="inside">C</span>
</span>
<span class="outside">
	<span class="inside">D</span>
</span>
&#13;
&#13;
&#13;

或者您可以像.inside

那样定位.outside + .outside .inside

&#13;
&#13;
span {
  display: block;
  background-color: bisque;
}
.outside + .outside .inside {
  background-color: red;
}
&#13;
<span class="outside">
	<span class="inside">A</span>
</span>
<span class="outside">
	<span class="inside">B</span>
</span>
<span class="outside">
	<span class="inside">C</span>
</span>
<span class="outside">
	<span class="inside">D</span>
</span>
&#13;
&#13;
&#13;