具有嵌套元素的 CSS nth-of-type 选择器

标签 css css-selectors

我有一些特定类 .box 的 div,我想为其设置交替背景色。然而,一些 div 被放置在另一个 div 内。inner-container:

<div class="container">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="inner-container">
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
    </div>
</div>

因此,使用 nth-of-type(even) 或 nth-child(even) 来更改每秒 .box 的颜色在这里不起作用。是否可以仅使用 CSS 实现交替背景?

注意:我不知道有多少盒子是 .container 的直接子代,有多少盒子在 .inner-container 中。

jsfiddle

最佳答案

I basically need a selector that counts the boxes as if they were all direct children of the same parent .container (as if the .inner-container would not exist).

假设只有一个内部容器 — 除了 .box.inner-container 之外没有其他元素 — 您将需要使用 : nth-child() 来确定它相对于它的 .box sibling (不是它的 .box child )的位置,从而决定是否以一种或另一种方式交替其内容的背景:

.container > .box:nth-child(even) {
    background-color: #bb3333;
}

.container > .inner-container:nth-child(odd) > .box:nth-child(even),
.container > .inner-container:nth-child(even) > .box:nth-child(odd) {
    background-color: #bb3333;
}

这是一个 demo为框贴上适当的标签,以便您了解每个选择器的工作原理。

请注意,如果您有任何可能出现在内部容器之后的框,您需要先计算出内部容器的 child 数量,然后才能确定如何开始计数从那时起。仅使用 CSS 是不可能的,因为 selectors cannot ascend from inner elements to outer elements .有使用 JavaScript 的解决方法,但我怀疑这超出了手头问题的范围。

关于具有嵌套元素的 CSS nth-of-type 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23986929/

相关文章:

html - 表 :last-child not working

selenium - 在 IE 中找不到元素,但在 FF 中工作正常

javascript - 我如何在不使用 JavaScript 的情况下使用 JQuery 库来重写它?

html - 水平对齐 DIV 容器内的文本

css - 带有 :target pseudo adding active style w/o Javascript 的标签

css - Safari 图片宽度变化

javascript - 根据特异性对一组 CSS 选择器进行排序

html - CSS:无法选择带有用户选择的子文本:自动,而父具有用户选择:无

mysql - 从特定 div 的 sql 数据库更改 css 背景

html - CSS-img :not selector?