Introduction
CSS variables, also known as custom properties, allow developers to store values in reusable variables. This enhances maintainability, flexibility, and efficiency in styling web pages.
1. Defining and Using CSS Variables
CSS variables are declared using the -- prefix inside a selector, typically :root for global scope.
Example:
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--font-size: 16px;
}
body {
background-color: var(--primary-color);
font-size: var(--font-size);
}CSSExplanation:
--primary-colorand--font-sizeare defined in:root, making them globally accessible.var(--primary-color)applies the stored value tobackground-color.
2. Local vs. Global Variables
Local Variables (Scoped within an Element)
Variables can be defined inside specific elements.
div {
--border-radius: 10px;
border-radius: var(--border-radius);
}CSSThis variable only applies within div elements.
3. Fallback Values in CSS Variables
If a variable is undefined, a fallback can be provided.
p {
color: var(--text-color, black);
}CSSHere, black is used if --text-color is not defined.
4. Modifying CSS Variables with JavaScript
CSS variables can be updated dynamically using JavaScript.
Example:
document.documentElement.style.setProperty('--primary-color', 'red');CSSThis changes --primary-color to red across the entire document.
5. Benefits of Using CSS Variables
- Reusability – Define once, use multiple times.
- Easy Theming – Change themes dynamically.
- Better Maintainability – Modify values in one place.
Conclusion
CSS variables enhance flexibility and efficiency in styling. They allow dynamic updates and make stylesheets cleaner and more maintainable.

