我有一个 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
类。
最佳答案
首先,让我解释一下为什么您到目前为止尝试过的选择器不起作用。 *-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;
}
下面的选择器会选择第一个、第三个、第五个、第七个元素等等。它们都有 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 所以他们的模式是 4n+3
。
.parent .head:nth-child(4n+1) {
background-color: gray;
}
.parent .head:nth-child(4n+3) {
background-color: darkgray;
}
<div class="parent">
<div class="head">A</div>
<div class="body">A</div>
<div class="head">A</div>
<div class="body">A</div>
<div class="head">A</div>
<div class="body">A</div>
<div class="head">A</div>
<div class="body">A</div>
</div>
关于html - 基于 nth-child(n) 选择器的替代颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35054683/