CSS Custom Properties, commonly known as CSS Variables, are a revolutionary way to manage and reuse values within your stylesheets. They allow you to define a value once and then reference it throughout your CSS, making your code more organized, maintainable, and dynamic.
Think of them as placeholders for values like colors, font sizes, spacing units, or even complex selectors. They start with two hyphens (--) and can be declared within any CSS selector, but are most commonly defined in the :root pseudo-class to make them globally available.
Here's how you declare a variable and then use it:
:root {
--primary-color: #007bff;
--base-spacing: 15px;
}
.my-element {
color: var(--primary-color);
padding: var(--base-spacing);
margin-bottom: var(--base-spacing);
border: 1px solid var(--primary-color);
}
--brand-accent instead of #f06292).Variables can be scoped to specific elements or selectors, allowing for more granular control. If a variable is declared on a specific element, it's only accessible to that element and its descendants.
.theme-dark {
--text-color: #eee;
--background-color: #333;
}
.theme-dark p {
color: var(--text-color);
background-color: var(--background-color);
padding: 10px;
}
Experiment with changing CSS variables in real-time. We'll adjust the background color and text color of the box below.