少 - 生成颜色的背景和边框类

时间:2013-06-04 18:33:06

标签: css less

我需要为~20种颜色创建类,但是对于每一种颜色,我需要创建两个 - 一个用于背景颜色,第二个用于边框。我知道我可以为每种颜色这样做:

@green: #00A300;

.green-background {
    background-color: @green;
}

.green-border {
    border: 1px solid @green;
}

但我认为应该有更有效的方法。像我这样的东西我指定变量,然后循环所有颜色并生成CSS到模式:

.[color]-background {
    background-color: [@color];
}

.[color]-border {
    border: 1px solid [@color];
}

这甚至可能吗?

1 个答案:

答案 0 :(得分:4)

对于使用Selector interpolation的mixin来说,这并不难:

<子> LESS:
.color(@name, @value) {
    //selector interpolation works when the entire
    //variable is used as the selector
    @bg-name: ~"@{name}-background";
    @border-name: ~"@{name}-border";

    .@{bg-name} {
        background-color: @value;
    }
    .@{border-name} {
        border: 1px solid @value;
    }
}
//be sure to quote the first parameter in case your color name gets
//interpreted as a value, blue would pass #00F which you don't want
.color('blue', #0000FF);
<子> CSS:
.blue-background {
  background-color: #0000ff;
}
.blue-border {
  border: 1px solid #0000ff;
}