css - LESS 使用类名声明变量?

标签 css variables less

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

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

Codepen Demo

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

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

关于css - LESS 使用类名声明变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25603517/

相关文章:

html - 背景的绝对位置

java - Java 中数组与非数组对象的变量范围

python - 循环访问一组具有相似名称的变量

html - CSS 优化问题

css - 如何从数组中选取随机内容

html - 任意子字符串属性值选择器在 IE7 中不起作用

javascript - jQuery .scroll 像电影一样改变背景

css - Bootstrap "col-md-4","col-xs-1", "col-lg-2"中数字的含义

python - Python 中如何解析对变量的引用

css - 传递一个空的 LESS 参数以使用默认值?