Last active
February 3, 2022 15:32
-
-
Save edanedison/1c80e32f88c683d20ce0 to your computer and use it in GitHub Desktop.
SASS Mixin to automatically create CSS utility classes based on a nested map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Brand | |
$primary: red; | |
$secondary: green; | |
$tertiary: blue; | |
// Colour variations | |
$shade-amount: 15%; | |
$trans-amount: 0.5; | |
// Palette Map | |
$colors: ( | |
primary: ( | |
base: $primary, | |
light: lighten($primary, $shade-amount), | |
dark: darken($primary, $shade-amount), | |
trans: transparentize($primary, $trans-amount) | |
), | |
secondary: ( | |
base: $secondary, | |
light: lighten($secondary, $shade-amount), | |
dark: darken($secondary, $shade-amount), | |
trans: transparentize($secondary, $trans-amount) | |
), | |
tertiary: ( | |
base: $tertiary, | |
light: lighten($tertiary, $shade-amount), | |
dark: darken($tertiary, $shade-amount), | |
trans: transparentize($tertiary, $trans-amount) | |
) | |
); | |
// MIXIN | |
// Quickly create utility classes based on the primary map keys; | |
// Pass in the map name, secondary key, then the utility class prefix and the attribute to create | |
@mixin createUtilities($map, $secondaryKey, $utilityClass, $attribute) { | |
@each $primaryKey, $val in $map { | |
.#{$utilityClass}-#{$primaryKey} { | |
#{$attribute}:#{map-get($val, $secondaryKey)}; | |
} | |
} | |
} | |
// USAGE | |
@include createUtilities($colors, 'base', 'u-bg', 'background-color'); | |
@include createUtilities($colors, 'base', 'u-text', 'color'); | |
// OUTPUT CSS | |
.u-bg-primary { | |
background-color: red; } | |
.u-bg-secondary { | |
background-color: green; } | |
.u-bg-tertiary { | |
background-color: blue; } | |
.u-text-primary { | |
color: red; } | |
.u-text-secondary { | |
color: green; } | |
.u-text-tertiary { | |
color: blue; } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I needed a way to automatically create utility classes without too much repetition in the sass. I also wanted to be able to add new items to the sass map and have the additional classes generated automatically.
You can probably extend this even further, but this did the job for me.