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.

Defining Variables

CSS variables use custom property names (starting with --) to declare:

Example

HTML
<style>
/* Define global variables in :root */
:root {
  --primary-color: #3498db;
  --secondary-color: #2ecc71;
  --text-color: #333;
  --border-radius: 8px;
  --spacing: 16px;
  --font-size: 16px;
}
</style>
▶ Try it Yourself

Using Variables

Reference variables using the var() function:

Example

HTML
<style>
.button {
  background-color: var(--primary-color);
  color: white;
  border-radius: var(--border-radius);
  padding: var(--spacing);
  font-size: var(--font-size);
}

.card {
  border: 1px solid var(--primary-color);
  border-radius: var(--border-radius);
  padding: var(--spacing);
}
</style>
<button class="button">Button</button>
<div class="card">Card</div>
▶ Try it Yourself

Variable Scope

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

Global variables — defined in :root:

Example

HTML
<style>
:root {
  --color: blue;
}
</style>
<div class="box-demo">Demo box showing current property effect</div>
▶ Try it Yourself

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

Example

HTML
<style>
.card {
  --card-bg: #f5f5f5;
  --card-padding: 20px;
}

.card-header {
  background: var(--card-bg);
  padding: var(--card-padding);
}
</style>
<div class="card">Card</div>
<div class="card-header">Card header</div>
▶ Try it Yourself

Variable Inheritance

CSS variables inherit like normal CSS properties:

Example

HTML
<style>
:root {
  --theme-color: #333;
}

/* Override variable in a container */
.dark-theme {
  --theme-color: #eee;
}

.dark-theme .content {
  color: var(--theme-color);  /* #eee */
}

.content {
  color: var(--theme-color);  /* #333 */
}
</style>
<div class="dark-theme">Dark theme preview</div>
<div class="content">Main content area</div>
▶ Try it Yourself

Fallback Values for var()

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

Example

HTML
<style>
.element {
  color: var(--undefined-color, red);  /* Uses red because --undefined-color is undefined */
  background: var(--bg, var(--fallback, #eee));  /* Can nest fallbacks */
}
</style>
<div class="element">This is an example element</div>
▶ Try it Yourself

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

JAVASCRIPT
// Get
const color = getComputedStyle(document.documentElement)
  .getPropertyValue('--primary-color');

// Set
document.documentElement.style.setProperty('--primary-color', '#e74c3c');
▶ Try it Yourself

Implementing Theme Switching

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

Example

HTML
<style>
/* Light theme (default) */
:root {
  --bg-color: #ffffff;
  --text-color: #333333;
  --card-bg: #f5f5f5;
  --border-color: #dddddd;
}

/* Dark theme */
[data-theme="dark"] {
  --bg-color: #1a1a2e;
  --text-color: #eeeeee;
  --card-bg: #16213e;
  --border-color: #0f3460;
}

body {
  background-color: var(--bg-color);
  color: var(--text-color);
}
</style>
▶ Try it Yourself

Then switch themes via JavaScript:

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

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

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 What's the difference between CSS variables 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.

📖 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.
100%

🙏 帮我们做得更好

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

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