我希望利用SASS规则(@mixin, @extend等)和/或控制指令(@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);
}
虽然我上面没有工作,但它更接近我想要完成的。有人解决了我要做的问题吗?任何见解将是非常感激,以及!
一个mixin就能搞定!
$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');