How to make multi-theme support using CSS variables

hi_iam_chris

Kristijan Pajtasev

Posted on February 18, 2021

How to make multi-theme support using CSS variables

Supporting multiple themes for your website is a difficult problem to solve. If you did it even a couple of years ago, you would agree with that. Quite often solution was to have wholly duplicated stylesheets. But that is messy. Maintaining an enormous stylesheet for each theme is not good. What if you have more than two. It is easy to miss some change and not notice it. It is also a performance issue. Unnecessary data to load. Thankfully, with CSS variables, this feature became much more comfortable to implement. And here is how.

Step 1: Setup

For this to work, you do need to spend some time organizing your CSS code. And that is to define your styling using CSS variables. You can read how to do this in my other article.

Step 2: Exclude CSS variables

You can define CSS variables in the same file where you are using them. But the better option is to exclude them as a separate file. Let’s call it variables.css. This way, replacing variables file changes the whole theme. Just remember to load them before you load the rest of the CSS.

<link  rel="stylesheet" href="/theme.css">
<link  rel="stylesheet" href="/variables.css">
Enter fullscreen mode Exit fullscreen mode

Step 3: Create other theme files

When your styling and variables are separated, you can create another file with values for a new theme. The problem, you can use only one variables file at a time. The last one defines the look.

<link  rel="stylesheet" href="/theme.css">
<link  rel="stylesheet" href="/variables.css">
<link  rel="stylesheet" href="/other-theme-variables.css">
Enter fullscreen mode Exit fullscreen mode

Step 4: Toggle active variable file

For toggling, first, you need to add an ID to the link element. Then you can use JavaScript to toggle the href attribute value. In this way, you only replace the used variables file without fully reloading the page. And your theme values get applied.

document.getElementById("themesID").href = "/other-theme.css"
Enter fullscreen mode Exit fullscreen mode

For more, you can follow me on Twitter, LinkedIn, GitHub, or Instagram.

💖 💪 🙅 🚩
hi_iam_chris
Kristijan Pajtasev

Posted on February 18, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related