First of all, lets code our ingredients into theme properties. Real themes used in this site will have plenty more properties, but lets show just a bit to keep things simpler:
( "primary-font": Raleway,
"primary-color": hsl(0, 0%, 19%),
"secondary-color": hsl(240, 0%, 63%) )
( "primary-font": Open Sans,
"primary-color": hsl(0, 69%, 67%),
"secondary-color": hsl(174, 62%, 40%) )
( "primary-font": Roboto Mono,
"primary-color": hsl(0, 0%, 5%),
"secondary-color": hsl(57, 90%, 60%) )
Then, we can create a collection of themes very easily. Lets save it in our _theme.scss
file:
$themeCollection: (
"bw": (/* Properties here */),
"peach-azure": (/* Properties here */),
"contrast": (/* Properties here */)
) !default;
Now its time to automatically bind these theme properties to real CSS properties. Here is where magic happens thanks to the SASS mixins. Mixins are just templates that you can reuse on
demand with the add-in of parameters, so we can create a smarter logic inside than just copy/paste chunks of code.
What if we do a generic mixin to themify whatever CSS property with theme values? Lets go for it! This is how the file _mixins.scss
will look like:
@import "themes";
$default-duration: 1.5s;
@mixin themify( $properties,
$keys,
$transition-duration: $default-duration,
$themes: $themeCollection)
{
// Iterate over the themes.
@each $theme, $themeItem in $themes {
// Create a selector CLASS-THEME and also THEME-CLASS.
&.theme-#{$theme},
.theme-#{$theme} & {
// Iterate over each property-key value.
@for $i from 1 through length($properties){
$property: nth($properties,$i);
$key: nth($keys,$i);
#{$property}: map-get($themeItem, $key);
}
// Finally add transitions over themified properties.
transition-property: #{$properties};
transition-duration: $transition-duration;
}
}
}
This code will generate, for every theme, a themified rule to assign the theme value(s) to every input CSS property(s). Note that I have also added transition effect to the themified properties to make theme changing
nicer (unfortunately, a font family change cannot be transitionated).