What are CSS Custom Properties (Variables)?
CSS Variables allow you to define reusable values right inside your CSS. Unlike variables in a preprocessor like Sass (which are compiled away), CSS Variables exist in the browser and can be updated with JavaScript in real-time.
They are defined with a double-hyphen prefix (e.g., --main-color) and accessed using the var() function. The best practice is to declare global variables on the :root pseudo-class, which represents the <html> element.
Code Snippet: Declaring and Using Variables
CSS
/* 1. Declare variables on the :root so they are globally available */
:root {
  --primary-bg-color: #ffffff;
  --primary-text-color: #333333;
  --accent-color: #007bff;
  --base-font-size: 16px;
}
/* 2. Use the variables throughout your stylesheet */
body {
  background-color: var(--primary-bg-color);
  color: var(--primary-text-color);
  font-size: var(--base-font-size);
}
a {
  color: var(--accent-color);
}
.button-primary {
  background-color: var(--accent-color);
  color: var(--primary-bg-color);
}
Implementing Dark Mode
The real power of CSS Variables shines when you want to change a theme. To create a dark mode, you simply need to redefine the variable values within a different scope. This can be done with a class or a media query.
Method 1: Using a Class (for a toggle button)
We can define a .dark-mode class on the <body> or <html> element and redefine our variables within that class.
Code Snippet: Theming with a Class
CSS:
CSS
/* Add this to your existing CSS */
.dark-mode {
  --primary-bg-color: #121212;
  --primary-text-color: #e0e0e0;
  --accent-color: #64b5f6;
}
JavaScript (to toggle the class):
JavaScript
const themeToggleBtn = document.getElementById('theme-toggle');
themeToggleBtn.addEventListener('click', () => {
  document.body.classList.toggle('dark-mode');
});
That's it! When the .dark-mode class is added to the body, all the elements using the var() function will instantly update to the new values.
Method 2: Respecting System Preference
You can also automatically switch to dark mode based on the user's operating system setting using the prefers-color-scheme media query.
Code Snippet: Using a Media Query
CSS
@media (prefers-color-scheme: dark) {
  /* You can set the dark theme as the default for users who prefer it */
  :root {
    --primary-bg-color: #121212;
    --primary-text-color: #e0e0e0;
    --accent-color: #64b5f6;
  }
}