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

How can I use CSS variables to theme a website and switch themes dynamically?

Asked on Oct 16, 2025

Answer

CSS variables, also known as custom properties, allow you to define reusable values for your styles, making it easy to implement and switch themes dynamically. Here's a basic example of how you can use CSS variables for theming.
<!-- BEGIN COPY / PASTE -->
    <style>
      :root {
        --primary-color: #3498db;
        --background-color: #ffffff;
      }

      .dark-theme {
        --primary-color: #2c3e50;
        --background-color: #34495e;
      }

      body {
        background-color: var(--background-color);
        color: var(--primary-color);
      }
    </style>

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

    <script>
      function toggleTheme() {
        document.body.classList.toggle('dark-theme');
      }
    </script>
    <!-- END COPY / PASTE -->
Additional Comment:
  • CSS variables are defined using the syntax "--variable-name: value;" and can be accessed using "var(--variable-name)".
  • The ":root" selector is often used to define global CSS variables that apply to the entire document.
  • JavaScript can dynamically toggle a class on the body element to switch themes by changing the values of CSS variables.
  • This approach allows for easy theme management and reduces the need for repetitive CSS code.
✅ Answered with CSS best practices.

← Back to All Questions
The Q&A Network