CSS Custom Properties Beyond Variables: Dynamic Theming and More
Custom properties are more than variables. They enable dynamic theming, responsive values, and patterns impossible with preprocessor variables. CSS custom properties, commonly called CSS variables, are often used as simple storage for repeated values, the way preprocessor variables have been used for years. Used that way, they are convenient but unremarkable. The real power of custom properties is that they are live, dynamic, and inheritable in ways preprocessor variables cannot be. After years of working with them, here are the patterns I use that go beyond simple variable substitution. Dynamic Theming With Cascading Variables The most impactful use of custom properties is dynamic theming. Because custom properties cascade and can be overridden at any selector, I can define a default theme at the root and override specific values in scoped contexts. A dark theme is just a redefinition of the semantic tokens. :root { --bg: #ffffff; --text: #111827; } [data-theme='dark'] { --bg: #121212; --text: #e0e0e0; } body { background: var(--bg); color: var(--text); } Switching themes is a matter of setting the data-theme attribute, which can be done instantly with JavaScript without reloading the page. Because the custom properties cascade, every element that references them updates automatically. More guides are on the Spark Blog.