CSS Questions & Answers Logo
CSS Questions & Answers Part of the Q&A Network
Q&A Logo

How can I use CSS variables to create a light/dark theme switcher for my website?

Asked on Oct 21, 2025

Answer

CSS variables, also known as custom properties, allow you to easily switch between themes by changing the values of these variables. Here's a simple example of how to implement a light/dark theme switcher using CSS variables.
<!-- BEGIN COPY / PASTE -->
    <style>
      :root {
        --background-color: white;
        --text-color: black;
      }

      .dark-theme {
        --background-color: black;
        --text-color: white;
      }

      body {
        background-color: var(--background-color);
        color: var(--text-color);
        transition: background-color 0.3s, color 0.3s;
      }
    </style>

    <button onclick="toggleTheme()">Toggle Theme</button>

    <script>
      function toggleTheme() {
        document.body.classList.toggle('dark-theme');
      }
    </script>
    <!-- END COPY / PASTE -->
Additional Comment:
  • Define CSS variables in the ":root" selector for default values.
  • Create a class (e.g., "dark-theme") with alternative values for the variables.
  • Use JavaScript to toggle the class on the "body" element to switch themes.
  • CSS transitions can be used for smooth color changes.
✅ Answered with CSS best practices.

← Back to All Questions
The Q&A Network