Custom Properties
Overview
Historically, developers used Sass ($primary-color: blue;) to create variables. However, Sass variables are compiled away on the server; they don't actually exist in the browser. CSS Custom Properties (CSS Variables) are a native browser feature. Because they live in the live DOM, they cascade, inherit, and most importantly, can be instantly updated via JavaScript or Media Queries at runtime. This single feature makes dynamic Dark Mode and White-Label theming incredibly easy.
Syntax
/* 1. Define Variables globally on the Root pseudo-class */
:root {
/* Syntax: Must start with double dashes (--) */
--brand-primary: #3b82f6;
--spacing-md: 16px;
--font-base: 'Inter', sans-serif;
}
/* 2. Using Variables */
.btn {
/* Syntax: var(--variable-name, fallback_value) */
background-color: var(--brand-primary);
padding: var(--spacing-md);
font-family: var(--font-base);
}
/* 3. Reassigning variables based on scope! */
.dark-theme-wrapper {
/* Any element inside this wrapper will naturally inherit this new value! */
--brand-primary: #93c5fd;
}Common Pitfalls
- Trying to use CSS Variables inside media query definitions (e.g.,
@media (max-width: var(--mobile-bp))). CSS Variables only exist in the DOM tree. Media queries evaluate against the browser window itself, so they cannot read variables. You must hardcode media queries (or use modern@custom-media). - Forgetting fallback values when building reusable components. If
--btn-colorisn't defined, the button will break. Usevar(--btn-color, blue)to ensure it always renders safely.
Interview Questions
$color) and a native CSS Variable (--color)?SCSS variables are statically compiled into hardcoded CSS strings before the website is deployed. Native CSS variables are dynamic, live in the browser's memory, cascade through the DOM, and can be updated in real-time by JavaScript.
Real-World Example
Implementing a flawless, instant Dark Mode toggle.
/* Define Light Mode defaults */
:root {
--bg-color: #ffffff;
--text-color: #000000;
}
/* When the user clicks the toggle, JS adds the 'dark' class to the <body> */
body.dark {
/* The variables instantly swap, repainting the entire app instantly! */
--bg-color: #121212;
--text-color: #ffffff;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
transition: background-color 0.3s ease;
}Check Your Knowledge
Test your understanding of Custom Properties with these quick questions.