CSS variables (also known as custom properties) allow you to store values for reuse throughout a stylesheet. They make it easier to manage and update styles.
Defining CSS variables:
Variables are defined in the :root
section or any selector.
:root { --primary-color: #3498db; --secondary-color: #2ecc71; }
Using CSS variables:
Variables are used with the var()
function.
.button { background-color: var(--primary-color); color: var(--secondary-color); }
Advantages of CSS variables:
- Easy style management: Variables allow for central management of values used repeatedly throughout the stylesheet.
- Dynamic changes: Variables can be dynamically updated using JavaScript.
- Inheritance: Variables can inherit values based on the context in which they are used.
Example of updating variables with JavaScript:
document.documentElement.style.setProperty('--primary-color', '#e74c3c');
CSS variables increase the flexibility and modularity of styles, making it easier to manage large projects.