Table of Contents
Implementing a theme switcher on your website enhances user experience by allowing visitors to choose between different visual styles, such as light and dark modes. Using CSS variables combined with JavaScript makes this process efficient and flexible. In this article, we’ll explore how to create a simple theme switcher using these technologies.
Understanding CSS Variables
CSS variables, also known as custom properties, are defined within a selector and can be reused throughout your stylesheet. They are particularly useful for theming because they allow dynamic changes to styles without modifying every rule. For example, you can define a color variable like this:
:root { --background-color: #ffffff; --text-color: #000000; }
Setting Up the HTML Structure
To enable theme switching, create buttons that users can click to select their preferred theme. Here’s a simple example:
<button id="light-theme">Light Mode</button>
<button id="dark-theme">Dark Mode</button>
And apply these styles to the page’s body:
<body> ... </body>
Implementing the JavaScript
Next, add JavaScript to listen for button clicks and change the CSS variables accordingly. Here’s a simple script:
const root = document.documentElement;
document.getElementById('light-theme').addEventListener('click', () => {
root.style.setProperty('--background-color', '#ffffff');
root.style.setProperty('--text-color', '#000000');
});
document.getElementById('dark-theme').addEventListener('click', () => {
root.style.setProperty('--background-color', '#222');
root.style.setProperty('--text-color', '#fff');
});
Applying CSS Variables to Styles
Finally, use the CSS variables in your stylesheet to apply the themes:
body {
background-color: var(--background-color);
color: var(--text-color);
}