更少使用类名声明变量? [英] LESS Declare variables using class names?

查看:78
本文介绍了更少使用类名声明变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a button class that sets up padding etc for an element, followed by a class that defines a background colour.

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

是否可以将@green变量声明为类名?这样一来,我就不必为要使用的每种颜色复制/粘贴& .green块.

Is it possible to declare the @green variable as the class name? This would save me having to copy/paste the &.green block for each colour I am wanting to use.

关于这种选择器,我还找不到任何文档,但是类似于:

I've not been able to find anything the docs regarding this sort of selector, but something along the lines of:

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

这将生成以下内容:

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

推荐答案

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

You could achieve this by having a variable with the required list of colors, a loop to create the required rules and selector interpolation like shown below.

@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演示

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

Note: As mentioned in comments, LESS PHP is quite outdated and hence some of the new features offered by LESS (with respect to loops) are not supported by it. It could be overcome by doing the work-around mentioned in this answer.

您还可以采用类似于 seven-phases-max 中提到的方法. a href ="https://stackoverflow.com/questions/23551080/how-to-thematize-in-lesscss">此答案(第二个选项).不用循环就可以达到类似的效果.

You could also adopt an approach similar to the one mentioned by seven-phases-max in this answer (2nd option). That one achieves a similar effect without using loops.

这篇关于更少使用类名声明变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆