首页 > 解决方案 > :nth-child() 以每三个项目为目标

问题描述

我试图定位.pricing-example页面上的每一个、第二个和第三个,以便为每个应用不同的背景颜色。但是,使用下面的代码,当.pricing-example页面上有 3 个元素时,nth-child(1n)目标项目 1 和 3,nth-child(3n)目标项目 2,我不明白。我想要实现的是在每三个项目上启用不同的背景颜色,如下所示:

HTML

<div class="blocks">
    <figure class="custom-block image"></figure>
    <figure class="custom-block text"></figure>
    <figure class="custom-block pricing-example"></figure>
    <figure class="custom-block pricing-example"></figure>
    <figure class="custom-block pricing-example"></figure>
</div>

CSS

.pricing-example {

    // Alternate background colours of images when multiple blocks
    &:nth-child(1n) {
        background-color: red;
    }
    &:nth-child(2n) {
        background-color: blue;
    }
    &:nth-child(3n) {
        background-color: green;
    }
}

标签: csssasscss-selectors

解决方案


伪类公式是(An+B)。每个MDN

对于 n 的每个正整数或零值,表示其在一系列同级中的数字位置与模式 An+B 匹配的元素。第一个元素的索引是 1。值 A 和 B 必须都是整数。

所以你想使用3n+1,3n+23n+3:

p:nth-child(3n+1) {
  background: red;
}

p:nth-child(3n+2) {
  background: blue;
}

p:nth-child(3n+3) {
  background: green;
}
<p>1</p>
<p>2</p>
<p>3</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>1</p>
<p>2</p>
<p>3</p>


推荐阅读