Skip to content

Instantly share code, notes, and snippets.

@dlewand691
Created February 3, 2022 15:32
Show Gist options
  • Save dlewand691/f85a2e0e29ea91877ab893a26680367a to your computer and use it in GitHub Desktop.
Save dlewand691/f85a2e0e29ea91877ab893a26680367a to your computer and use it in GitHub Desktop.
SASS Mixin to automatically create CSS utility classes based on a nested map
// 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