CSS Custom Properties & Variables
16 min read
CSS VariablesCustom PropertiesThemingDark Mode:rootvar()JavaScript Integration
The Power of CSS Variables
CSS Custom Properties (variables) are not just a convenience — they are a runtime feature that can be read and updated with JavaScript, cascade through the DOM, and enable theming systems.
CSS Variables vs Sass Variables
| Feature | CSS Variables | Sass Variables |
|---|---|---|
| When resolved | Runtime (browser) | Compile time (build) |
| Can change dynamically | ✅ Yes (JS, media queries) | ❌ No |
| Cascade/inherit | ✅ Yes | ❌ No |
| Scope | DOM tree (CSS selectors) | File/block scope |
| Fallback values | ✅ var(--x, fallback) | N/A |
| Performance | Tiny overhead | Zero (compiled away) |
Scoping
Variables cascade and inherit just like regular CSS properties. Define them on :root for global scope, or on specific selectors for component scope.
Dark Mode with CSS Variables
The most elegant dark mode implementation: define colors as variables, swap them with a selector or media query.