π Introduction
The var() function in CSS is used to access values stored in CSS Custom Properties (variables). It allows you to reuse values across your stylesheet, update themes dynamically, and make your CSS scalable and maintainable. When combined with --variable-name, var() becomes one of the most powerful tools in modern CSS. π¨β¨
π― What Does var() Do?
- Fetches the value of a CSS variable
- Supports fallback values
- Works in all CSS properties
- Makes themes easy to update and manage
- Can be dynamically changed with JavaScript
β¨ Syntax
Syntax
property: var(--variable-name, fallback-value);Note
π§© Basic Usage
1. Defining a Variable
Define Variable
:root {
--primary-color: #4f46e5;
}2. Using the Variable
Use Variable
button {
background-color: var(--primary-color);
}π₯ Using Fallback Values
Fallbacks are extremely helpful when a variable may not exist or when you want guaranteed output.
Fallback Example
color: var(--text-color, #222);If --text-color is missing, it defaults to #222.
π§© Practical Examples
1. Theme Colors
Theme Example
:root {
--bg: #ffffff;
--text: #111827;
}
body {
background: var(--bg);
color: var(--text);
}2. Dark Mode Override
Dark Mode
.dark {
--bg: #0f172a;
--text: #f8fafc;
}
body {
background: var(--bg);
color: var(--text);
}3. Spacing System
Spacing Tokens
:root {
--space-sm: 8px;
--space-md: 16px;
--space-lg: 32px;
}
.card {
padding: var(--space-md);
margin-bottom: var(--space-lg);
}4. Dynamic Size with calc()
var() + calc()
:root {
--base-size: 10px;
}
.box {
width: calc(var(--base-size) * 12);
}5. Gradients Using Variables
Gradient With Variables
:root {
--start: #06b6d4;
--end: #3b82f6;
}
.hero {
background: linear-gradient(to right, var(--start), var(--end));
}π§ How var() Works with Scope
CSS variables inherit β meaning nested elements can use parent variables.
Scoped Variable
.card {
--card-bg: #e2e8f0;
}
.card .header {
background: var(--card-bg);
}Note
β‘ Using var() with JavaScript
You can update CSS variables via JavaScript in real-time.
JS Update
document.documentElement.style
.setProperty('--primary-color', '#ef4444');π var() Function Summary Table
| Feature | Details |
|---|---|
| Retrieves variable | var(--name) |
| Supports fallback | var(--name, fallback) |
| Works everywhere | colors, spacing, gradients, calc() |
| Dynamic | Can update via JavaScript |
| Inherits | Follows CSS cascade |
π§ Best Practices
- Use :root for global tokens
- Group variables (colors, spacing, typography)
- Use fallbacks to avoid rendering issues
- Use variables for consistent spacing and font sizes
- Great for dark mode and theme switching
π Conclusion
The var() function is the key to using CSS Custom Properties effectively. Whether you're building a design system, implementing dark mode, or writing cleaner CSS, mastering var() makes your styles more flexible, maintainable, and powerful. π Combine it with --variable-name and you unlock modern, scalable CSS.