Introduction


In my previous post, I explained a CSS trick to quickly implement a dark mode on your website. I also said that it could be interesting to offer multiple themes options.

In this post, I am going to present a simple CSS variables system that will allow you to implement theming.

Here is a live demo of this tutorial on Codepen : https://codepen.io/estellepicq/pen/RwRypzw


CSS variables


We are going to use CSS variables. It is a custom property defined as follow:

 --main-bg-color: #fff;


Then, we can use it like this:

.element {
  background-color: var(--main-bg-color);
}


Theming implementation


A theme is a set of colors that we want to apply on the different components of our website: backgrounds, fonts, borders...

We can define a main theme, that will be the default theme when we first land on the website:

:root {
  --bg-color: #fff;
  --font-color: #404040;
  --primary-color: #3f51b5;
}


Here, the variables are defined at root level, and it allows us to use it globally.

We are going to use it on the body element:

body {
 background-color: var(--bg-color);
 color: var(--font-color);
}


Then, we define a class for elements that will have a special color:

.primary-color {
 color: var(--primary-color);
}


We can now set a dark theme, which will also be available in all the document, when data-theme attribute is equal to 'dark'.

[data-theme=”dark”] {
  --bg-color: #404040;
  --font-color: #fff;
  --primary-color: #3f51b5;
}


All is left to do is to implement the JavaScript logic behind the action of switching themes.

document.documentElement.setAttribute('data-theme', 'dark');



Dig deeper: store chosen theme as a preference


In order to keep the chosen theme as a user preference, we can store it in the browser local storage:

localStorage.setItem('theme', 'dark');


That way, when the page load, we can then get this value and apply it to the document:

var theme = localStorage.getItem(‘theme’);
document.documentElement.setAttribute('data-theme', theme); 


Conclusion


Now you know how to quickly implement a CSS variables theming system 🎉!


I showed in this post a really simple example with two themes and three variables properties, but you can for sure adapt this example for your specific needs and implements many themes with a lot more of variable colors!


Have fun.