如何对条件循环使用更少的预处理器



div{
display: inline-block;
border: 1px solid black;
height: 100px;
width: 100px;
}
#div1, #div2, #div3{
background: red;
}
#div4, #div5, #div6{
background: blue;
}
<html>
<body>
<div id="div0">0</div>
<div id="div1">1</div>
<div id="div2">2</div>
<br><br>
<div id="div3">3</div>
<div id="div4">4</div>
<div id="div5">5</div>
</body>
</html>

出于练习原因,我想使用更少的时间使第一行div 为红色,使第二行为蓝色。 我研究了文档并编写了以下代码:

.generate-colors(6);
.generate-colors(@n, @i:0)when(@i<@n){
.div@{i}{
background: red;
}
.generate-colors(@n, (@i+1));
}

@i大于 2 时,如何将背景颜色设置为蓝色?

你实际上并不需要 LESS; 你可以利用CSS的nth-of-type()伪类和n + 4来选择你的第二行元素:body > div:nth-of-type(n + 4)。现有的两个红色元素可以用n + 2.这可以从下面看出:

div {
display: inline-block;
border: 1px solid black;
height: 100px;
width: 100px;
}
body > div:nth-of-type(n + 2) {
background: red;
}
body > div:nth-of-type(n + 4) {
background: blue;
}
<html>
<body>
<div id="div0">0</div>
<div id="div1">1</div>
<div id="div2">2</div>
<br><br>
<div id="div3">3</div>
<div id="div4">4</div>
<div id="div5">5</div>
</body>
</html>

就 LESS 而言,您可以使用以下方法执行此操作:

body {
>div {
&:nth-of-type(n {
&+2) {
background: red;
}
&+4) {
background: blue;
}
}
}
}

只需做两次相同的事情:

.generate-colors1(2);
.generate-colors1(@n, @i:0)when(@i<@n){
.div@{i}{
background: red;
}
.generate-colors1(@n, (@i+1));
}
.generate-colors2(6);
.generate-colors2(@n, @i:3)when(@i<@n){
.div@{i}{
background: blue;
}
.generate-colors2(@n, (@i+1));
}

最新更新