Blog>
Snippets

Using CSS Variables for Theming

Create an example of how to use CSS variables in a theme switcher to illustrate the importance of CSS preprocessor skills.
:root {
  --background-color: white;
  --text-color: black;
}

.dark-theme {
  --background-color: black;
  --text-color: white;
}
Defines CSS variables for color schemes. The default theme colors are set in the :root pseudo-class, and an alternative dark theme is defined in a separate class.
document.querySelector('#theme-switch').addEventListener('click', function() {
  // Toggle the 'dark-theme' class on the body element
  document.body.classList.toggle('dark-theme');
});
Attaches an event listener to a button with the id 'theme-switch'. When the button is clicked, the class 'dark-theme' is toggled on the body element, which switches the theme.