目前我有一个 LESS 的片段,它基本上将每个后续的 child 从顶部进一步向下移动:
&:nth-child(n+2) {
top: @alertTop + 10px;
}
&:nth-child(n+3) {
top: @alertTop + 20px;
}
&:nth-child(n+4) {
top: @alertTop + 30px;
}
有没有办法在计算中使用“n+x”的“x”部分,这样我就不必手动添加这些?
即像这样的东西:
&:nth-child(n+x) {
top: @alertTop + (x * 5px);
}
首选 LESS/CSS only 方法。
最佳答案
From the documentation : 创建一个调用自身的 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);
}
结果
#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;
}
关于css - 使用 :nth-child(n + x) pseudo class 内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27400860/