基于nth-child(n)选择器的替代颜色

Joh*_*ego 3 html css css-selectors css3

我有一个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>
Run Code Online (Sandbox Code Playgroud)

我想.head用交替的灰色和深灰色进行着色.

我的CSS有问题吗?

.parent .head:nth-child(2n) {
   background-color: gray;
}
.parent .head {
   background-color: dark-gray;
}
Run Code Online (Sandbox Code Playgroud)

我也习惯odd

.parent .head:nth-child(odd) {
   background-color: gray;
}
Run Code Online (Sandbox Code Playgroud)

但它也算上了.body课程.

Har*_*rry 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>
Run Code Online (Sandbox Code Playgroud)

这意味着下面的选择器不会选择任何元素,因为2n选择了第2,第4,第6,第8个元素,但这些元素没有class='head'.

.parent .head:nth-child(2n) {
   background-color: gray;
}
Run Code Online (Sandbox Code Playgroud)

下面的选择器将选择第1,第3,第5,第7个元素,依此类推.它们都有,class='head'但问题是所有.head元素都是其父元素的奇数子元素,因此这会将样式应用于所有.head元素而不会产生交替的颜色效果.

.parent .head:nth-child(odd) {
   background-color: gray;
}
Run Code Online (Sandbox Code Playgroud)

鉴于您的元素具有固定模式,您可以使用4n+14n+3 作为第n个子选择器的参数并设置元素的样式.

识别an+b模式的逻辑非常简单.在你的结构中,第1,第5,第9 ......元素需要有一种颜色,而第3,第7,第11 ......元素需要有另一种颜色.我们可以看到,每个数字之间的差异是4,因此乘法因子是4.第一系列元素与4n系列1 不同,因此选择它们的模式是,4n+1而另一系列元素与4n3系列不同,因此它们的模式是4n+3.

.parent .head:nth-child(4n+1) {
  background-color: gray;
}
.parent .head:nth-child(4n+3) {
  background-color: darkgray;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)