我正在尝试使用nth-of-type
为其他.time
和.title
元素设置灰色背景(奇数/偶数模式)。
<div class="calendar">
<div class="time">Gray Background</div>
<div class="title">Gray Background</div>
<div class="time">White Background</div>
<div class="title">White Background</div>
<div class="time">Gray BG</div>
<div class="title">Gray BG</div>
<div class="time">White Background </div>
<div class="title">White Background</div>
</div>
答案 0 :(得分:5)
nth-of-type()
伪类不识别类。它只关心作为同一父(source)的孩子的元素。
此外,在这种情况下,您不需要将课程与nth-of-type
匹配。
根据您的HTML结构,您似乎需要2x2斑马条纹。
因此,将每个元素设置为灰色,然后用白色覆盖每个第4和第4个:
div > div {
background-color: lightgray;
}
div > div:nth-child(4n),
div > div:nth-child(4n-1) {
background-color: white;
}
&#13;
<div class="calendar">
<div class="time">Gray Background</div>
<div class="title">Gray Background</div>
<div class="time">White Background</div>
<div class="title">White Background</div>
<div class="time">Gray BG</div>
<div class="title">Gray BG</div>
<div class="time">White Background</div>
<div class="title">White Background</div>
<div class="time">Gray Background</div>
<div class="title">Gray Background</div>
<div class="time">White Background</div>
<div class="title">White Background</div>
<div class="time">Gray BG</div>
<div class="title">Gray BG</div>
<div class="time">White Background</div>
<div class="title">White Background</div>
</div>
&#13;
答案 1 :(得分:0)
:nth-of-type
匹配elemnt名称,而不是类。
:nth-of-type(an + b)CSS伪类匹配一个元素,该元素在文档树类型<之前具有相同元素名称的+ b-1兄弟< / p>
解决此问题的一种方法是将item
和time
包装在一个元素中,如下所示:
.appointment:nth-of-type(odd){
background: gray;
}
&#13;
<div class="calendar">
<div class="appointment">
<div class="time">Gray Background</div>
<div class="title">Gray Background</div>
</div>
<div class="appointment">
<div class="time">White Background</div>
<div class="title">White Background</div>
</div>
<div class="appointment">
<div class="time">Gray Background</div>
<div class="title">Gray Background</div>
</div>
<div class="appointment">
<div class="time">White Background</div>
<div class="title">White Background</div>
</div>
</div>
&#13;