在 :nth-child(n + x) 伪类中使用变量

Ada*_*all 5 css css-selectors less

目前我有一个 LESS 片段,它基本上会将每个后续子项从顶部向下移动:

    &:nth-child(n+2) {
        top: @alertTop + 10px;
    }

    &:nth-child(n+3) {
        top: @alertTop + 20px;
    }

    &:nth-child(n+4) {
        top: @alertTop + 30px;
    }
Run Code Online (Sandbox Code Playgroud)

无论如何在计算中使用“n+x”的“x”部分,以便我不必手动添加这些?

即类似:

    &:nth-child(n+x) {
        top: @alertTop + (x * 5px);
    }
Run Code Online (Sandbox Code Playgroud)

首选 LESS/CSS 方法。

Sal*_*n A 3

从文档中:创建一个调用自身的 mixin 以及一个保护表达式:

较少的

#test {
  @child-count: 5;
  @child-height: 100px;
  position: relative;
  height: @child-count * @child-height;
  > div {
    position: absolute;
    left: 0;
    right: 0;
    height: @child-height;
    background: red;
  }
  .loop(@i) when (@i <=5) {
    > :nth-child(@{i}) {
      top: (@i - 1) * @child-height;
    }
    .loop(@i + 1);
  }
  .loop(1);
}
Run Code Online (Sandbox Code Playgroud)

结果

#test {
  position: relative;
  height: 500px;
}
#test > div {
  position: absolute;
  left: 0;
  right: 0;
  height: 100px;
  background: red;
}
#test > :nth-child(1) {
  top: 0px;
}
#test > :nth-child(2) {
  top: 100px;
}
#test > :nth-child(3) {
  top: 200px;
}
#test > :nth-child(4) {
  top: 300px;
}
#test > :nth-child(5) {
  top: 400px;
}
Run Code Online (Sandbox Code Playgroud)

代码笔