Learn how to use CSS custom properties (variables) to create more maintainable and dynamic stylesheets
--
) prefix, and are accessed using the var()
function.
:root
selector to make them globally available, but they can be defined in any selector:
var()
function:
:root
selector are globally available throughout the document:
var()
function accepts a second parameter that serves as a fallback value if the variable is not defined:
calc()
function for dynamic calculations:
Feature | CSS Variables | Preprocessor Variables |
---|---|---|
Runtime updates | ✅ Can be updated with JavaScript | ❌ Compiled before runtime |
Cascade & inheritance | ✅ Follow CSS inheritance rules | ❌ Static at compile time |
Scope | ✅ Scoped to the selector | ❌ Usually global or limited by preprocessor scope |
Browser support | ✅ All modern browsers | ✅ Compiled to standard CSS |
Computed values | ✅ Can be computed in browser | ❌ Computed at compile time |
Debugging | ✅ Visible in browser dev tools | ❌ Not visible after compilation |