我有一个按钮类,它为元素设置填充等,后跟一个定义背景颜色的类。
.button {
padding: 0.5em 1em;
text-transform: uppercase;
color: #fff;
&.green {
background:@green; //declared previously
}
// ... more colours
}
是否可以将@green 变量声明为类名?这将使我不必为我想使用的每种颜色复制/粘贴 &.green block 。
我没能找到关于这种选择器的任何文档,但大致如下:
&.(green|blue|red) {
background: @{$1};
}
这将生成以下内容:
.button.green{background:#00ff00;}
.button.blue{background:#0000ff;}
.button.red{background:#ff0000;}
最佳答案
您可以通过具有所需颜色列表的变量、创建所需规则的循环和选择器插值来实现此目的,如下所示。
@colors: "green","blue","orange","red","yellow"; // the list of colors required
button {
padding: 0.5em 1em;
text-transform: uppercase;
.loop-colors(@index) when (@index > 0){ // loop to generate rules for each color
.loop-colors(@index - 1); // call for the next iteration
@color: e(extract(@colors, @index)); // pick the color value from the list one by one based on current index
&.@{color} {
background:@color;
}
}
.loop-colors(length(@colors));
}
注意:如评论中所述,LESS PHP 已经过时,因此它不支持 LESS 提供的一些新功能(关于循环)。它可以通过执行 this answer 中提到的解决方法来克服。 .
您也可以采用类似于 seven-phases-max 提到的方法在 this answer (第二个选项)。那个在不使用循环的情况下实现了类似的效果。
关于css - LESS 使用类名声明变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25603517/