CSS Variables, also known as Custom Properties, are entities defined in CSS that store reusable values. They allow developers to centralize values like colors, fonts, and sizes, making CSS easier to maintain and update.
Syntax:
Declaring a Variable: CSS variables are prefixed with --
and are usually defined in a global scope, such as the :root
pseudo-class.
:root {
--primary-color: #3498db;
--font-size: 16px;
}
Using a Variable: To use a variable, the var()
function is applied.
h1 {
color: var(--primary-color);
font-size: var(--font-size);
}
Fallback Value: You can add a fallback value in case the variable is not defined.
h1 {
color: var(--secondary-color, #333);
}
How to Update CSS Variables Dynamically with JavaScript
Define the Variable in CSS: Use :root
(global scope) or a specific selector to declare your variable.
:root {
--primary-color: #3498db;
}
Access and Modify the Variable with JavaScript: Use the setProperty
method on the style
object of the desired element.
// Access the root element
const root = document.documentElement;
// Update the CSS variable
root.style.setProperty('--primary-color', '#ff0000');
Advantages of CSS Variables
Maintainability: Change the variable’s value in one place, and it updates across the entire project.
Consistency: Promotes consistent design by centralizing styles.
Theme Switching: Simplify creating themes (e.g., light mode, dark mode).
Dynamic Updates: JavaScript can modify variables in real-time for interactive effects.