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

How can I use CSS variables to change theme colors dynamically?

Asked on Oct 02, 2025

Answer

CSS variables, also known as custom properties, allow you to define reusable values that can be dynamically changed to update theme colors across your website.
<!-- BEGIN COPY / PASTE -->
    <style>
      :root {
        --primary-color: #3498db;
        --secondary-color: #2ecc71;
      }

      body {
        background-color: var(--primary-color);
        color: var(--secondary-color);
      }

      .theme-dark {
        --primary-color: #2c3e50;
        --secondary-color: #ecf0f1;
      }
    </style>

    <body>
      <div class="theme-toggle">
        <button onclick="toggleTheme()">Toggle Theme</button>
      </div>
      <script>
        function toggleTheme() {
          document.body.classList.toggle('theme-dark');
        }
      </script>
    </body>
    <!-- END COPY / PASTE -->
Additional Comment:
  • CSS variables are defined using the syntax "--variable-name: value;" within a selector, often ":root" for global scope.
  • To use a CSS variable, apply "var(--variable-name)" in your styles.
  • JavaScript can manipulate CSS variables by toggling classes or directly updating styles, enabling dynamic theme changes.
  • Ensure that the CSS variables are defined in a scope that matches their intended use, such as globally or within specific classes.
✅ Answered with CSS best practices.

← Back to All Questions
The Q&A Network