css nth-child 或 nth-of-type

标签 css wordpress css-selectors

我想避免在自定义 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/

相关文章:

python - selenium.common.exceptions.ElementNotVisibleException : Message: element not visible while invoking send_keys in ubuntu headless browser through python

javascript - Twitter Bootstrap 隐藏水平滚动

html - css 将一个表居中放置在一个 div 中,并将该 div 居中放置在另一个 div 中

html - CSS 对齐搜索框

html - 占位符 CSS 调用问题

python - 无法正确解析某些元素的名称

html - 显示的动态字段和值组

php - Woocommerce:从插件获取一些自定义购物车项目数据值

php - 使用 ajax 重新加载和 WordPress 插件

mysql - wp_usermeta 查询在加载前挂起几秒钟