CSS Variables
Introduction to CSS Variables
Custom properties (variables) allow you to store reusable values in CSS.
Syntax
Define variables using --variable-name
inside a selector: :root { '--main-color': '#3490dc' }
.
Using Variables
Use a variable with the var()
function: color: var(--main-color);
Fallbacks
Provide a fallback value: color: var(--undefined, black);
Benefits
CSS variables improve code readability, maintainability, and enable dynamic theming.
- DRY (Don't Repeat Yourself): Define a value once, reuse it everywhere.
- Easier Theming: Change themes by updating a few variables.
- Dynamic Updates: Variables can be updated with JavaScript.
Scope
Variables defined in :root
are global. Variables defined within a specific selector are local to that selector and its descendants.
:root {
--global-color: blue; /* Global */
}
.element {
--local-color: red; /* Local to .element and children */
color: var(--local-color);
border-color: var(--global-color);
}
JavaScript Interaction
You can get and set CSS variables using JavaScript.
// Get a variable from the :root element
const rootStyles = getComputedStyle(document.documentElement);
const mainColor = rootStyles.getPropertyValue('--main-color');
// Set a variable on an element
const element = document.querySelector('.my-element');
element.style.setProperty('--custom-bg', 'lightblue');