CSS: CSS Variables
CSS Variables (Custom Properties) let you define reusable values in CSS, similar to variables in programming languages. Using CSS variables can greatly reduce repetitive code and make it easy to manage design tokens like theme colors and spacing.
1. Defining Variables
CSS variables use custom property names (starting with --) to declare:
▶ Example
▶ Try it Yourself2. Using Variables
Reference variables using the var() function:
▶ Example
▶ Try it Yourself3. Variable Scope
CSS variable scope is determined by where they're defined:
Global variables — defined in :root:
▶ Example
▶ Try it YourselfLocal variables — defined in a specific selector, only effective in that selector and its children:
▶ Example
▶ Try it Yourself4. Variable Inheritance
CSS variables inherit like normal CSS properties:
▶ Example
▶ Try it Yourself5. Fallback Values for var()
var() can set a second parameter as a fallback — used when the variable is undefined:
▶ Example
▶ Try it Yourself6. Modifying Variables with JavaScript
data-theme attribute on <html>, use variables in CSS to reference different colors, and one line of JS code can switch the entire site's color scheme.
A major advantage of CSS variables is that they can be dynamically modified via JavaScript:
▶ Example
▶ Try it Yourself7. Implementing Theme Switching
CSS variables are the best way to implement theme switching like "dark mode":
▶ Example
▶ Try it YourselfThen switch themes via JavaScript:
document.documentElement.setAttribute('data-theme', 'dark');
// or
document.documentElement.setAttribute('data-theme', 'light');
8. Advantages of CSS Variables
- Reduce repetitive code: One variable used in many places, change once to update all
- Runtime modifiable: Can be dynamically changed via JS for theme switching
- Scope control: Can override variable values in specific containers
- Semantic:
--primary-coloris easier to understand than#3498db
9. Differences from Preprocessors
CSS Variables (Custom Properties) differ from Sass/Less variables:
| Feature | CSS Variables | Sass Variables |
|---|---|---|
| Runtime modification | ✅ Yes | ❌ Fixed after compilation |
| Scope | ✅ CSS inheritance | ❌ Fixed values after compilation |
| Browser | Modern browser support | No browser support needed (pre-compiled) |
| JS interaction | ✅ Readable/writable | ❌ Not accessible |
❓ FAQ
:root { --primary-color: #3498db; } and use with color: var(--primary-color);. Names must start with -- and are case-sensitive — --Color and --color are two different variables. Variables on :root are available site-wide, and the value can be any valid property value: colors, lengths, you name it.:root are globally available; variables defined on an element only take effect in that element and its children. This property enables local theme overrides — give a container different variable values, and all references to those variables inside automatically change.:root, override them with dark values in [data-theme="dark"], then one line of JavaScript document.documentElement.dataset.theme = "dark" can switch the entire site's color scheme.color: var(--missing, red); uses red when the variable doesn't exist. With no fallback and an undefined variable, the declaration is treated as invalid-at-computed-value time — it inherits what it should or falls back to the initial value, failing silently with no console error. Give theme-related variables a fallback to survive load-order hiccups.--c: #fff, spacing --gap: 12px, a whole font stack --font: system-ui, sans-serif, even a complete shadow --shadow: 0 2px 8px rgba(0,0,0,0.2); — define once, reference everywhere. Bare numbers like --n: 2 pair with calc: width: calc(var(--n) * 100px);.getComputedStyle(el).getPropertyValue('--primary'), write with el.style.setProperty('--primary', '#e74c3c'). Changing a variable on documentElement reskins the whole site — that one line is the engine behind theme toggle buttons, far cleaner than swapping classes element by element.width: calc(var(--base) * 2 + 10px); uses the variable as a number in math. In calc, multiply/divide only by unitless numbers: calc(var(--w) * 2) is valid, calc(var(--w) * 2px) is not. Responsive layouts love this for shared spacing: padding: calc(var(--gap) * 2); — change one variable and every gap on the site follows.--color vs --Color); referencing outside the scope (the variable lives on some container, so outsiders can't see it); syntax errors in either the fallback or the value that void the whole declaration; or simply the wrong property name. The Computed panel in DevTools shows the resolved variable values and invalid markers, so you can see exactly which layer broke.📖 Summary
- CSS variables are very important tools in modern CSS development
- Defined with
--variable-name, used withvar(), they make style code cleaner and easier to maintain - The greatest value: change one value, and all places referencing that variable automatically update
- Theme switching, responsive color schemes, unified design language — CSS variables are especially useful in large projects
📝 Exercises
- Create a page using CSS variables to define at least 5 variables for theme colors, text colors, spacing, etc., and use them throughout the page.
- Based on the above page, implement "one-click theme color switching" — modify the primary color variable in
:rootand observe changes in all related elements. - Use CSS variables to implement a simple "day/night" mode switch (by switching class or data-theme attribute via JS).
- Locally override CSS variable values in a container (like a card component) and observe style changes in its child elements.