What are Custom Properties?
Custom Properties, commonly known as CSS Variables, allow you to store specific values (colors, sizes, fonts) and reuse them throughout your stylesheet. Unlike SASS/LESS variables, CSS variables are dynamic and exist in the browser's DOM, meaning they can be changed via JavaScript.
1. Declaration and Usage
Variables are defined starting with
-- and accessed using the var() function. Usually, global variables are defined in the :root pseudo-class.css
2. Scoping and Inheritance
One of the most powerful features of CSS variables is Scoping. You can redefine a variable inside a specific selector, and it will only affect that element and its children.
css
3. Dynamic Changes with JavaScript
Since variables are part of the DOM, you can update them instantly with JS, which is perfect for Dark Mode toggles or interactive animations.
javascript
4. Fallback Values
You can provide a second argument to
var() as a fallback if the variable isn't defined.css
Comparison: CSS Variables vs. SASS Variables
| Feature | CSS Variables | SASS Variables ($) |
|---|---|---|
| Runtime | Dynamic (Browser) | Static (Compiled) |
| DOM Access | Yes (via JS) | No |
| Scoping | Cascading (Inherited) | Block-scoped |
| Performance | Native | Zero runtime cost |
Summary Checklist
- Use
--nameto define andvar(--name)to use. - Define global variables in
:root. - Use scoping for modular component themes.
- Perfect for Dark Mode and dynamic theming.
- Combine with
calc()for powerful responsive layouts. - Supported in all modern browsers.