CSS variables make repeated values easier to manage
CSS custom properties—usually called CSS variables—let you name a value and reuse it throughout a stylesheet. They are especially useful for colours, spacing, and other values that need to stay consistent.
Define site-wide variables on :root with names beginning with --:
:root {
--primary-color: #333;
--secondary-color: #999;
}
Then read them with var():
body {
color: var(--primary-color);
}
a {
color: var(--secondary-color);
}
Change --primary-color once and every declaration using it updates. That is the obvious benefit, but custom properties can do more because they participate in the cascade.
For example, a component can inherit the site colour or override it locally:
.notice {
--primary-color: rebeccapurple;
border-color: var(--primary-color);
}
You can also provide a fallback and use a custom property inside calc():
.card {
gap: var(--card-gap, 1rem);
width: calc(100% - var(--page-padding));
}
JavaScript can change a value with setProperty(), which makes custom properties useful for themes and interactive controls. I still prefer defining the normal state in CSS and using JavaScript only when the value genuinely depends on user interaction.