CSS Variables, also known as custom properties, allow you to store reusable values and apply them dynamically. They make your styles more maintainable, scalable, and customizable.
- and are usually declared in the :root pseudo-class for global access.:root {
--primary-color: #3498db;
--secondary-color: #e74c3c;
--font-size: 16px;
}
var() function:body {
color: var(--primary-color);
font-size: var(--font-size);
}
💡 Tip: If a variable is not defined, you can provide a fallback value:
p {
color: var(--text-color, black); /* Uses black if --text-color is undefined */
}
CSS variables can be scoped to specific elements. A locally defined variable will override the global variable inside that scope.
:root {
--main-color: #3498db; /* Global variable */
}
div {
--main-color: #e74c3c; /* Scoped only to div elements */
}
p {
color: var(--main-color); /* Uses the closest defined --main-color */
}
✅ Reusability → Define once, use everywhere.
✅ Maintainability → Update a single value to update all related styles.