2016-11-16 34 views
3

我期待利用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); 
} 

虽然我上面没有工作,它更接近我尝试做的事情。有人解答我在这里试图做什么?任何有识之士都会非常感激!

回答

3

一个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');