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.
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.
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">
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">
document.getElementById("themesID").href = "/other-theme.css"