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

How can I use CSS variables (custom properties) to simplify theme colors?

Asked on Aug 30, 2025

Answer

CSS variables, also known as custom properties, allow you to define reusable values throughout your stylesheet, making it easier to manage theme colors. Here's how you can use them effectively.
<!-- BEGIN COPY / PASTE -->
    <style>
      :root {
        --primary-color: #3498db;
        --secondary-color: #2ecc71;
        --text-color: #333;
      }

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

      .button {
        background-color: var(--secondary-color);
        color: white;
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
      }
    </style>

    <body>
      <h1>Welcome to My Themed Page</h1>
      <button class="button">Click Me</button>
    </body>
    <!-- END COPY / PASTE -->
Additional Comment:
  • CSS variables are defined within a selector using the syntax --variable-name: value;.
  • The :root selector is commonly used to define global variables that apply to the entire document.
  • To use a CSS variable, reference it with the var() function, e.g., var(--primary-color).
  • CSS variables can be updated dynamically with JavaScript, allowing for theme switching without reloading the page.
  • They are supported in all modern browsers, making them a robust choice for styling.
✅ Answered with CSS best practices.

← Back to All Questions
The Q&A Network