我有一个div
,其替代班级名称是1个父母。
<div class="parent">
<div class="head"></div>
<div class="body"></div>
<div class="head"></div>
<div class="body"></div>
<div class="head"></div>
<div class="body"></div>
<div class="head"></div>
<div class="body"></div>
</div>
我想用交替的灰色和深灰色为所有.head
着色。
我的CSS有问题吗?
.parent .head:nth-child(2n) {
background-color: gray;
}
.parent .head {
background-color: dark-gray;
}
我还使用了odd
来实现此目标
.parent .head:nth-child(odd) {
background-color: gray;
}
但它也会计算.body
类。
答案 0 :(得分:8)
首先,让我解释一下为什么到目前为止您尝试过的选择器无法正常工作。 *-child
选择器仅基于元素而不是附加到其上的额外条件。因此,在您的情况下,.head
元素是其父母下的第1,第3,第5,第7个孩子。
<div class="parent">
<div class="head"></div> <!-- this is always the 1st child of its parent -->
<div class="body"></div> <!-- this is always the 2nd child of its parent -->
<div class="head"></div> <!-- this is always the 3rd child of its parent -->
<div class="body"></div> <!-- this is always the 4th child of its parent -->
<div class="head"></div> <!-- this is always the 5th child of its parent -->
<div class="body"></div> <!-- this is always the 6th child of its parent -->
<div class="head"></div> <!-- this is always the 7th child of its parent -->
<div class="body"></div> <!-- this is always the 8th child of its parent -->
</div>
这意味着下面的选择器不会选择任何元素,因为2n
选择了第2,第4,第6,第8个元素,但这些元素没有class='head'
。
.parent .head:nth-child(2n) {
background-color: gray;
}
以下选择器将选择第1,第3,第5,第7个元素,依此类推。它们都有class='head'
,但问题是所有.head
元素都是其父级的奇数子元素,因此这会将样式应用于所有.head
元素,而不会产生交替的颜色效果
.parent .head:nth-child(odd) {
background-color: gray;
}
鉴于您的元素具有固定模式,您可以使用4n+1
和4n+3
作为第n个子选择器的参数并为元素设置样式。
识别an+b
模式的逻辑非常简单。在你的结构中,第1,第5,第9 ......元素需要有一种颜色,而第3,第7,第11 ......元素需要有另一种颜色。我们可以看到,每个数字之间的差异是4,因此乘法因子是4
。第一系列元素与4n
系列的区别为1,因此选择它们的模式为4n+1
,而另一系列元素与4n
系列的区别为3,因此它们的模式为{ {1}}。
4n+3
&#13;
.parent .head:nth-child(4n+1) {
background-color: gray;
}
.parent .head:nth-child(4n+3) {
background-color: darkgray;
}
&#13;