LESS使用类名声明变量?

时间:2014-09-01 10:13:18

标签: css variables less

我有一个按钮类,为元素设置填充等,然后是一个定义背景颜色的类。

.button {
    padding: 0.5em 1em;
    text-transform: uppercase;
    color: #fff;
    &.green {
        background:@green; //declared previously
    }
    // ... more colours
}

是否可以将@green变量声明为类名?这样可以省去我为每种颜色复制/粘贴& .green块。

我无法找到关于这种选择器的文档,但有些内容如下:

&.(green|blue|red) {
    background: @{$1};
}

会生成以下内容:

.button.green{background:#00ff00;}
.button.blue{background:#0000ff;}
.button.red{background:#ff0000;}

1 个答案:

答案 0 :(得分:2)

您可以通过使用具有所需颜色列表的变量,创建所需规则的循环和选择器插值来实现此目的。如下所示。

@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));
}

Codepen Demo

注意:正如评论中所提到的,LESS PHP已经过时了,因此它不支持LESS提供的一些新功能(关于循环)。可以通过this answer中提到的解决方法来克服它。

您也可以采用类似于seven-phases-max this answer中提到的方法(第二选项)。那个在不使用循环的情况下实现了类似的效果。

相关问题