1

我需要为大约 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];
}

这甚至可能吗?

4

1 回答 1

4

这对于使用Selector 插值的 mixin 来说并不难:

较少的:
.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;
}
于 2013-06-04T18:55:34.880 回答