CSS Themes as white label

Recently, I had to add white-label support for the project.

This means, that some elements on screen had to be able to get theme-specific styling. Usually this mainly means theme-specific colors, but this can easily be extended to SVGs, graphics, Logos etc.

So, I came up with a neat CSS trick I’ll go over today.

In the code snippets, I used SCSS but this can very easily be converted to standard css. Doing so is beyond the scope of this post.

The basic idea is to create separate set of css rules per theme and apply the correct theme set according to the currently selected theme at runtime.

So, the HTML would look something like:
Screen Shot 2016-05-03 at 21.47.23
Note we define the app on line 1 and the controller on line 2.
The magic happens on lines 3 and 9.

On line 3, we apply a app-{{themeName}}-theme css rule that is dynamic depending on the value of demo.appId on the controller scope.
On line 9, we apply the title css rule.
The checkboxes in between are just a simple means to change the themes at runtime to see it in action.

Next, the controller code:
Screen Shot 2016-05-03 at 21.54.48
Here, we initialize the app and the controller, simply setting values to the name and the appId.

The third piece of the puzzle, is the css itself:
Screen Shot 2016-05-03 at 21.57.17
On line 1 we create a mixin that gets the app-name and button-color as arguments and creates the set of css rules we mentioned earlier.

When we invoke it for theme1 on line 10, the app-theme1-theme css rule is included and inside it a css rule for the title with the color red.
When it is invoked again for theme2 on line 11, the app-theme2-theme css rule is included and inside it a css rule for the title with the color green. The same goes for the third theme with the color blue.

This completes the cycle and when we select a different theme using the radio buttons, the appId value on the scope is changed and as a result the appropriate theme css rule is applied thus also changing the title text color.

You can see it in action in this jsBin.

As always, feel free to use and abuse 🙂
If you modify jsBlackBelt code, please let me know or submit a pull request for the benefit of others.

Leave a comment