Чтобы получить тот же результат, что и в первом примере, есть две опции:
Вариант 1
Сделать простой одноразовый mixin
:
$brand_col: (
def: blue,
mus: red,
ser: yellow
);
@mixin branding {
@each $brand, $col in $brand_col {
&.#{$brand} {
background: $col;
}
}
}
.body {
@include branding;
}
Это скомпилируется в:
.body.def {
background: blue;
}
.body.mus {
background: red;
}
.body.ser {
background: yellow;
}
Вариант 2
Создайте повторно mixin
, чтобы вы могли передать цветовую карту для применения:
$brand_colors: (
def: blue,
mus: red,
ser: yellow
);
@mixin branding($colors) {
@each $class, $color in $colors {
&.#{$class} {
background: $color;
}
}
}
.body {
@include branding($brand_colors);
}
// Latter you can use it to apply the same 'branding' for any other element
div {
@include branding($brand_colors);
}
Будет компилироваться в:
.body.def {
background: blue;
}
.body.mus {
background: red;
}
.body.ser {
background: yellow;
}
div.def {
background: blue;
}
div.mus {
background: red;
}
div.ser {
background: yellow;
}
Вы можете даже внедрить второй параметр в mixin
, чтобы указать, какое свойство css
вы хотите применить, с background
по умолчанию:
@mixin branding($colors, $property: background) {
@each $class, $color in $colors {
&.#{$class} {
#{$property}: $color;
}
}
}
// Latter you can use it to apply the same 'branding' for any other element and property
h1 {
@include branding($brand_colors, color);
}
Будет компилироваться в:
h1.def {
color: blue;
}
h1.mus {
color: red;
}
h1.ser {
color: yellow;
}
Вы можете узнать больше о миксин здесь .
Надеюсь, это поможет!