Skip to content
css questions

CSS · 5 of 10junior~1 min

What are CSS custom properties (variables) and how do they work?

#core#variables

CSS Custom Properties

CSS custom properties (variables) store reusable values and can be changed dynamically.

Syntax

css
/* define - always start with -- */ :root { --color-primary: #3b82f6; --color-text: #1a1a1a; --spacing-md: 16px; --border-radius: 8px; } /* use */ .button { background-color: var(--color-primary); padding: var(--spacing-md); border-radius: var(--border-radius); } /* fallback value */ .card { color: var(--color-accent, #ff0000); /* uses #ff0000 if --color-accent is not defined */ }

Scoping - variables are inherited

css
:root { --color: blue; } .card { --color: red; /* overrides only inside .card */ } .card p { color: var(--color); } /* red */ p { color: var(--color); } /* blue */

Dynamic theming

css
:root { --bg: white; --text: black; } [data-theme='dark'] { --bg: #1a1a1a; --text: white; } body { background: var(--bg); color: var(--text); }
js
// change theme at runtime document.documentElement.setAttribute('data-theme', 'dark'); // update a variable directly document.documentElement.style.setProperty('--color-primary', '#ff0000');

CSS variables are the foundation of modern theming systems. Unlike Sass variables, they are live in the browser and can be changed with JavaScript at runtime.

updated

did you know it?

related questions