css nth-child或nth-of-type

时间:2014-04-23 06:05:12

标签: css wordpress css-selectors

我想避免在自定义Wordpress模板中使用函数或循环来显示某个元素的不同背景颜色。我的问题是需要更改的容器及其父容器。

每个第1,第4,第7等配置文件类需要具有蓝色的背景颜色。每个第2,第5,第8等配置文件类需要具有红色的背景颜色。每隔3日,6日,9日等都需要背景颜色为绿色。

我尝试过使用.profile:nth-​​child和.profile:nth-​​of-type的不同组合,但只有2个类的子类实例重置了背景颜色。

目前,我得到了类似的内容:

<div class="staff">
    <div class="profile">
    (blue)
    </div>
    <div class="profile">
    (red)
    </div>
</div>
<div class="staff">
    <div class="profile">
    (blue)
    </div>
    <div class="profile">
    (red)
    </div>
</div>
<div class="staff">
    <div class="profile">
    (blue)
    </div>
    <div class="profile">
    (red)
    </div>
</div>
....

当我想看到的是:

<div class="staff">
    <div class="profile">
    (blue)
    </div>
    <div class="profile">
    (red)
    </div>
</div>
<div class="staff">
    <div class="profile">
    (green)
    </div>
    <div class="profile">
    (blue)
    </div>
</div>
<div class="staff">
    <div class="profile">
    (red)
    </div>
    <div class="profile">
    (green)
    </div>
</div>
....

1 个答案:

答案 0 :(得分:2)

这有点复杂,但假设每个.staff元素最多只包含2个.profile元素,it can be done - 即使.staff组开始重复:< / p>

.staff:nth-child(3n+1) .profile:nth-child(1),
.staff:nth-child(3n+2) .profile:nth-child(2) {
    background-color: blue;
}

.staff:nth-child(3n+1) .profile:nth-child(2),
.staff:nth-child(3n+3) .profile:nth-child(1) {
    background-color: red;
}

.staff:nth-child(3n+2) .profile:nth-child(1),
.staff:nth-child(3n+3) .profile:nth-child(2) {
    background-color: green;
}

请注意,假设:nth-of-type()元素是其父级中唯一的.staff元素,div将无法发挥作用,因为:nth-of-type()仅查看标记名称,无论如何,您的所有.profile元素也都是div

相关问题