在两个div之间交替使用行颜色

4

我不确定这是否可以使用CSS实现,但如果可以,我希望能得到一些帮助。

我有类似以下的HTML代码:

<div class="group"></div>

<div class="group"></div>
<div class="group subgroup"></div>
<div class="row"></div>
<div class="row"></div>

<div class="group"></div>
<div class="group subgroup"></div>
<div class="row"></div>

是否可以交替更改行类的背景颜色?始终以相同的颜色开始?我一直在使用nth-child尝试实现这一点,但我认为这是由于组/子组类。

以下是可返回的示例数据集的手动html标记和设计样式的jsfiddle: http://jsfiddle.net/Qr5Za/

2个回答

4
“始终以相同颜色开始”意味着在组/子组后的第一行以红色开头。 如果是这样,您可以通过以下方式将第一个.row的background-color设置为红色,其它行设置为品红色: ```CSS .row:first-child { background-color: red; } .row:not(:first-child) { background-color: magenta; } ```
.group ~ .row { /* select all rows comes after each group */
    background-color: magenta;
}

.group + .row { /* select and override the first row after each group */
    background-color: red;
}

JSBin演示

这些选择器被称为一般兄弟选择器 ~相邻兄弟选择器 +,您可以在这里找到更多详细信息

更新

所有新的CSS3选择器如:nth-child(n):nth-of-type(n) 匹配其父元素中是第n个子级或类型的每个元素。

所以实现这个,唯一的方法是将每个块的.row放入一个包装器中:

<div class="group">This is a group</div>
<div class="group subgroup">This is a subgroup</div>
<div class="wrap">
  <div class="row">This is the first row</div>
  <div class="row">This is the second row</div>
  <div class="row">This is the third row</div>
  <div class="row">This is the forth row</div>
</div>

根据它们在.wrapper (它们的父元素)中的位置,选择oddeven行:

.row:nth-child(odd) {
  background-color: red;
}

.row:nth-child(even) {
  background-color: magenta;
}

JSBin演示 #2


行的HTML标记将动态创建,在此示例中,如果我在第一子组之后添加第三行,则停止交替颜色。 - Ryan
是的,没错。如果手动标记,我可以期望看到数据,并希望像这样显示它,例如http://jsfiddle.net/Qr5Za/。 - Ryan
这非常有帮助,我之前很困惑,让我想一下。 - Hashem Qolami
1
你和我一样都想了很久,最终得出了相同的结论,真是让人费解。 - brbcoding
这就是在玩了一段时间后的正确方法。感谢Hashem Qolami和@brbcoding的帮助。 - Ryan
显示剩余4条评论

1
.row:nth-of-type(n) + .row:nth-of-type(even){
  background: green;
}

.row:nth-of-type(n) + .row:nth-of-type(odd){
  background: orange;
}
.group.subgroup + .row:nth-of-type(n) {
  background: blue;
}

更新演示


所以“始终以相同的颜色开始”意味着分组/子组后的第一行以红色开始。我有一些东西基本上可以工作,但它总是根据内容交替变化。 - Ryan
与这里的其他答案类似,如果我在第一子组中添加另一行标记,您会发现第一行以绿色开头,而第二个子组后面的第二行以红色开头。 - Ryan
编辑!所以我改变了代码,将第一行与相邻的行变成了绿色,并添加了第五行,它仍然在子组之间交替。http://jsfiddle.net/SRAKn/ - Ryan
还不太对...把最后一个的背景改成绿色,你就会明白我的意思了。 - brbcoding
嗯,刚注意到。哎呀。 - Ryan
我不想说,但我感到困惑... 我认为如果没有实际将每个组包装在自己的容器中,这是无法完成的。-- 不过,我很乐意被证明是错误的。 - brbcoding

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接