我有一些特定类 .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 中。
最佳答案
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/