Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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; }
@edanedison

This comment has been minimized.

Copy link
Owner Author

commented Nov 6, 2015

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.