我希望利用SASS规则(@mixin,@ expand等)和/或控制指令(@ if,@ for,@each等)为我定义的颜色变量生成类
以下是我目前正在使用的示例,但我知道我可以进一步简化此操作,以减少冗余。
// Colors
$navy: #37455a;
$blue: #abbdd3;
$cyan: #a3d9cb;
$peach: #ff9d7a;
// Backgrounds
.bg-navy{
background: $navy;
}
.bg-blue{
background: $blue;
}
.bg-cyan{
background: $cyan;
}
.bg-peach{
background: $peach;
}
// Text
.text-navy{
color: $navy;
}
.text-blue{
color: $blue;
}
.text-cyan{
color: $cyan;
}
.text-peach{
color: $peach;
}
我尝试了一些不同的方法,但我总是遇到与映射的冲突。我想保留对象中的映射变量,以便在这些函数之外使用。这是我到目前为止所提出的:
// Colors for use in other partials
$navy: #37455a;
$blue: #abbdd3;
$cyan: #a3d9cb;
$peach: #ff9d7a;
// Mapped colors used for generating classes (Duplicated unfortunately)
$colors: (
$navy: #37455a;
$blue: #abbdd3;
$cyan: #a3d9cb;
$peach: #ff9d7a;
)
// Background class definition
@mixin bg{
.bg-#{$color}{
background: $color;
}
}
// Text class definition
@mixin text{
.text-#{$color}{
color: $color;
}
}
// Background class generation
@each $color in $colors{
@include bg($color);
}
// Text class generation
@each $color in $colors{
@include text($color);
}
虽然我上面的内容不起作用,但它更接近我想要完成的事情。有没有人解决我在这里尝试做的事情?任何见解都会受到高度赞赏!
答案 0 :(得分:6)
一个混合就可以做到这一切!
$navy: #37455a;
$blue: #abbdd3;
$cyan: #a3d9cb;
$peach: #ff9d7a;
$colors: (
navy: $navy,
blue: $blue,
cyan: $cyan,
peach: $peach
);
@mixin gen-props($prefix, $property) {
@each $color-name, $color in $colors {
.#{$prefix}-#{$color-name} {
#{$property}: $color
}
}
}
@include gen-props('text', 'color');
@include gen-props('bg', 'background');