我想避免在自定义 Wordpress 模板中使用函数或循环来为特定元素显示不同的背景颜色。我的问题是需要更改的容器及其父容器。
每个第 1、4、7 等配置文件类都需要有蓝色背景色。每个第 2、5、8 等配置文件类都需要有红色背景色。每第 3、6、9 等需要有绿色背景色。
我试过使用 .profile:nth-child 和 .profile:nth-of-type 的不同组合,但在 staff 父类中只有 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>
....
最佳答案
这有点复杂,但假设每个 .staff
元素最多只包含 2 个 .profile
元素,it can be done — 即使 .staff
组开始重复:
.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;
}
请注意,假设您的 .staff
元素是唯一的 div
元素,:nth-of-type()
不会产生任何影响在它们的父级中,因为 :nth-of-type()
只查看标签名称,而你所有的 .profile
元素也是 div
无论如何。
关于css nth-child 或 nth-of-type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23236051/