CSS: CSS Variables

🗓 Last updated: 2026-11-30👤 Written by: Blake✓ Reviewed by: Gray🏷 Category: CSS Tutorial

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 Yourself

2. Using Variables

Reference variables using the var() function:

▶ Example

▶ Try it Yourself

3. Variable Scope

CSS variable scope is determined by where they're defined:

Global variables — defined in :root:

▶ Example

▶ Try it Yourself

Local variables — defined in a specific selector, only effective in that selector and its children:

▶ Example

▶ Try it Yourself

4. Variable Inheritance

CSS variables inherit like normal CSS properties:

▶ Example

▶ Try it Yourself

5. Fallback Values for var()

var() can set a second parameter as a fallback — used when the variable is undefined:

▶ Example

▶ Try it Yourself

6. Modifying Variables with JavaScript

✅ Theme switching implementation: CSS variables combined with JavaScript is the best solution for implementing "dark mode" — toggle the 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 Yourself

7. Implementing Theme Switching

CSS variables are the best way to implement theme switching like "dark mode":

▶ Example

▶ Try it Yourself

Then switch themes via JavaScript:

JAVASCRIPT
document.documentElement.setAttribute('data-theme', 'dark');
// or
document.documentElement.setAttribute('data-theme', 'light');

8. Advantages of CSS Variables

  1. Reduce repetitive code: One variable used in many places, change once to update all
  2. Runtime modifiable: Can be dynamically changed via JS for theme switching
  3. Scope control: Can override variable values in specific containers
  4. Semantic: --primary-color is 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

Q How do I define and use CSS variables, and how does var() work?
A Define with :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.
Q What's the difference between CSS custom properties and Sass variables?
A CSS variables are true CSS properties that can be dynamically modified in the browser and support JavaScript read/write. Sass variables become fixed values after compilation and cannot be modified at runtime. CSS variables can do theme switching; Sass variables cannot. They don't conflict and can be used together.
Q What are the scope rules for CSS variables?
A CSS variables follow cascading rules. Variables defined in :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.
Q Can CSS variables implement dark mode?
A Yes, this is the most classic use case for CSS variables. Define light color variables in :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.
Q What happens when var() references an undefined variable? How do I write a fallback?
A The second argument is the fallback: 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.
Q What kinds of values can CSS variables hold — only colors?
A Any valid property value: colors --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);.
Q How do I read and modify CSS variables with JavaScript?
A Read with 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.
Q How do calc() and var() work together?
A 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.
Q My variable-based style isn't applying — how do I debug it?
A The four usual suspects: a typo or case mismatch in the name (--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

📝 Exercises

  1. 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.
  2. Based on the above page, implement "one-click theme color switching" — modify the primary color variable in :root and observe changes in all related elements.
  3. Use CSS variables to implement a simple "day/night" mode switch (by switching class or data-theme attribute via JS).
  4. Locally override CSS variable values in a container (like a card component) and observe style changes in its child elements.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏