CSS Custom Properties (Variables) Cheat Sheet
Covers declaring and scoping CSS custom properties, fallback values, reading/writing them from JavaScript, and typed properties with @property.
2 PagesBeginnerMar 15, 2026
Basic Declaration & Usage
Define once, reuse everywhere, with a fallback.
css
:root { --brand-color: #6366f1; --spacing-unit: 8px; --max-width: 1200px;}.card { color: var(--brand-color); padding: calc(var(--spacing-unit) * 2); /* Fallback is used only if --unknown is not defined at all */ border-color: var(--unknown, #ccc);}
Scoping & Theming
Custom properties cascade and can be overridden per subtree.
css
/* Global tokens */:root { --color-primary: #2563eb;}/* Component-scoped override, only affects .card and its descendants */.card { --color-primary: #059669; background: var(--color-primary);}.card--dark { --color-primary: #10b981;}
Reading & Writing from JavaScript
Custom properties are live values in the DOM.
javascript
const root = document.documentElement;// Read a custom property (returns a string; trim whitespace)const color = getComputedStyle(root).getPropertyValue('--color-primary').trim();// Set/update a custom property at runtimeroot.style.setProperty('--color-primary', '#f43f5e');// Remove an inline override, falling back to the cascaded valueroot.style.removeProperty('--color-primary');
@property (Typed Custom Properties)
Register a syntax so the value can be animated smoothly.
css
@property --progress { syntax: '<percentage>'; inherits: false; initial-value: 0%;}.bar { width: var(--progress); transition: --progress 0.3s ease; /* animatable because it's typed */}.bar.loaded { --progress: 75%;}
Key Facts & Gotchas
Behavior that trips people up coming from Sass variables.
- Inheritance- Custom properties inherit by default, and follow normal cascade/specificity rules
- Case-sensitive- --Color and --color are two different custom properties
- var() fallback- var(--x, fallback) only applies when --x is unset, not when its value is invalid
- Runtime updates- Unlike Sass variables, custom properties are live and can be read/changed with JavaScript
- No custom properties in media queries- var() cannot currently be used inside @media conditions
Pro Tip
Use @property to declare a syntax and initial value for custom properties you want to animate — the browser only interpolates typed values like <percentage> or <color> smoothly; plain untyped custom properties jump instantly with no interpolation.
Was this cheat sheet helpful?
Explore Topics
#CSSCustomPropertiesVariables#CSSCustomPropertiesVariablesCheatSheet#WebDevelopment#Beginner#BasicDeclarationUsage#ScopingTheming#ReadingWritingFromJavaScript#Property#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance