I am looking to utilize a SASS Rules (@mixin, @extend, etc.) and/or control directives (@if, @for, @each, etc.) to generate classes for the color variables that I have defined.
Below is an example of what I am using currently, but I know that I can further simplify this to make it significantly less redundant.
// 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;
}
I have tried a few different methods, but I always run into conflicts with mapping. I want to preserve the mapped variable in the object to use outside of these functions. This is what I have come up with so far:
// 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);
}
While what I have above does not work, it's closer to what I am trying do accomplish. Has anybody solved for what I am attempting to do here? Any insight would be much appreciated as well!
One mixin to do it all!
$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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With