CSS Variables Cheatsheet
complete CSS custom properties reference with examples
By Bikram NathLast updated
A syntax reference for CSS custom properties covering declaration, `var()` usage, fallback chains, and JavaScript read/write. Handy when you need to look up the exact JS call to read a variable at runtime: `getComputedStyle(el).getPropertyValue('--spacing-base').trim()` returns the computed string including any whitespace. Unlike generic CSS references, this cheatsheet surfaces the two-argument fallback form and the `el.style.setProperty()` write path in one place.
Try it now — free, instant, no signup
What is CSS Variables Cheatsheet?
The CSS Variables Cheatsheet is a focused reference for CSS custom properties syntax — how to declare them (`--token-name: value` inside any selector, not just `:root`), consume them with `var(--token-name)`, define fallback chains, and bridge them into JavaScript with `getComputedStyle` and `setProperty`. A concrete example: declare `--theme-bg: #1a1a1a` on a `.dark` class, then read it in a canvas script to keep JS color values in sync with CSS without duplicating literals.
When you need to understand a specific syntax edge case, this cheatsheet is faster than scanning MDN's full custom properties article or the CSS Cascading Variables spec. MDN covers the same ground but includes browser compatibility tables and extended prose; reach for MDN when you need historical browser support or spec citations. Sass and Less docs cover preprocessor variables, which look similar but are a different concept entirely.
The most common gotcha is the fallback comma rule: `var(--font, Georgia, serif)` has a single fallback value of `Georgia, serif` — everything after the first comma is the fallback, not a list of separate fallbacks. This surprises developers expecting each comma-separated item to be tried in order. A second sharp edge: custom properties cannot appear in media query conditions. `@media (max-width: var(--bp-md))` is invalid and silently ignored; breakpoints must be hardcoded or set via JavaScript on a container element.