CSS variables (custom properties) store values you reuse: color, space, radius, fonts. Declare them on :root or a theme class, read them with var(--name, fallback), and override them on a subtree for dark mode or branded sections without rewriting every rule.
This CSS cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- Declare:
--color-bg: #fff;on:rootor.theme-dark. - Use:
color: var(--color-text);Invalid if the variable is missing and you omitted a fallback. - Fallback:
var(--space, 1rem)is used when--spaceis not set (or is invalid at computed time). - Scope: Properties inherit. Set
--accenton.sidebarto recolor only that tree. - Units:
calc(var(--step) * 2)works. You cannot do--w: 10thenwidth: var(--w)pxwithout registering or calc tricks. - Theming: Toggle
data-theme="dark"onhtmland remap tokens — keep component CSS the same. - JS:
element.style.setProperty("--progress", "40%")for live values. - @property: Optional typed custom properties for animation and validation in supporting browsers.
Copy-paste examples
Tokens plus a dark theme class
Component rules stay token-based. Only the mapping changes under .theme-dark.
:root {
--bg: #ffffff;
--text: #0f172a;
--accent: #2563eb;
--space: 1rem;
}
.theme-dark {
--bg: #0f172a;
--text: #e2e8f0;
--accent: #93c5fd;
}
body {
background: var(--bg);
color: var(--text);
padding: var(--space);
}
.badge {
color: var(--badge-fg, var(--text));
}Common mistakes
- Hardcoding hex in components after you already defined tokens — themes will miss those rules.
- Expecting
var(--x)to work inside media query parentheses in older browsers (use a preprocessor or duplicate). - Putting
--properties on a selector that never wraps the elements you style. - Animating a custom property that is not registered with
@propertyand wondering why it snaps.
FAQ
- CSS variables vs Sass variables? Sass is compile-time. CSS variables are live in the browser and can be changed with JS or a parent class. Use both: Sass for structure, CSS vars for theme.
- What happens if a variable is invalid? The property is invalid at computed-value time and may fall back to inherited or initial — plus your
var()fallback if provided.
- Can I store entire font stacks? Yes.
--sans: system-ui, sans-serif;thenfont-family: var(--sans);.
Related CSS cheat sheets
Build with this stack
When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds custom web development and also sells ready-made source code. Request a quote and tell us the stack.
Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.