CSS Variables & Custom Properties
Learn CSS Custom Properties (--vars). Master scoping to :root, var() fallbacks, dynamic JavaScript updates, and instant Light/Dark theme switching patterns.
CSS Custom Properties In-Depth Overview & Use Cases
CSS Custom Properties (commonly referred to as CSS Variables) bring dynamic values directly into native stylesheets without needing Sass or Less preprocessors. Custom properties start with a double dash (e.g. --brand-color) and can be accessed anywhere using the var() function.
Unlike preprocessor variables which compile down to static CSS values at build time, native CSS variables live in the DOM cascade. They can be updated dynamically at runtime via JavaScript, overridden inside specific component scopes, or swapped instantly using media queries for Dark Mode themes.
Key Real-World Use Cases
Defining centralized color palettes, spacing scales, and font stacks on the :root element.
Swapping surface and text variables when a [data-theme="dark"] attribute is added to the <html> tag.
Overriding scoped variables inside card or button modifier classes.
Updating mouse cursor coordinates or scroll percentage variables directly from JavaScript event listeners.
Declaring & Using Variables (:root Scope & var())
Custom properties declared on the :root pseudo-class become globally available across the entire document cascade.
Light / Dark Mode Theme Switching Pattern
Because CSS variables participate in the cascade, swapping an attribute on <html> or <body> instantly updates all components across the entire website.
Dynamic Control via JavaScript
JavaScript can read and update CSS variables in real time using getPropertyValue() and setProperty():