The CSS var() function
The CSS var() function reads a custom property — a variable you define with a -- prefix — so you can reuse a value everywhere and change it in one place. var(--brand, #1c7ce9) supplies a fallback if --brand is not set. Custom properties cascade and can be updated at runtime, which makes var() the backbone of theming and dark mode.
Overview
Custom properties — names that start with -- — are CSS variables, and var() is how you read them. Define --brand: #1c7ce9 once (usually on :root) and reference it anywhere with var(--brand). Change the definition in one spot and every use updates, which is the whole appeal.
var() takes an optional second argument: a fallback used when the property is not defined. var(--brand, #1c7ce9) reads as "use --brand, or this blue if it does not exist." That keeps components resilient when a token is missing.
What sets custom properties apart from a preprocessor variable is that they are live. They inherit through the DOM, they can be redefined inside a media query, and they can be read and written from JavaScript. That is exactly how dark mode works: redefine a handful of -- tokens inside @media (prefers-color-scheme: dark) and the whole interface re-themes itself, no extra CSS required.
Syntax
/* define once, reuse everywhere */
:root {
--brand: #1c7ce9;
--space: 16px;
}
.btn {
background: var(--brand);
padding: var(--space);
}
Example
<style>
.panel {
--brand: #6d28d9;
background: var(--brand);
color: #fff;
border-left: 6px solid var(--accent, #c4b5fd);
padding: 18px 20px;
border-radius: 10px;
font: 15px/1.5 system-ui, sans-serif;
}
</style>
<div class="panel">The background and border both read <code>var(--brand)</code> — change it once to retheme.</div>
Best practices
- Define design tokens (colors, spacing, radii) once on
:rootand reference them withvar()so changes happen in one place. - Provide a fallback as the second argument for resilience, e.g.
var(--brand, #1c7ce9). - Redefine tokens inside
@media (prefers-color-scheme: dark)for an effortless dark mode. - Remember custom properties can be read and set from JavaScript with
getPropertyValue/setPropertyfor dynamic theming.
Frequently asked questions
How do I use CSS variables?
--brand: #1c7ce9 (often on :root), then read it anywhere with var(--brand).How do I set a fallback for a CSS variable?
var(--brand, #1c7ce9) uses the blue if --brand is not defined.Can I change CSS variables with JavaScript?
element.style.setProperty("--brand", "#16a34a") to update one, which re-themes everything that reads it.