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.
Enjoyed reading this?
If you found this article helpful, consider supporting my writing. Every little bit helps keep this blog going.
Related articles
- Better Line Breaks With CSS balance and pretty
Use text-wrap balance for short headings and text-wrap pretty selectively for longer copy without hard-coded line breaks.
- Why 100vh Doesn’t Always Fit a Mobile Screen
Choose svh, lvh, dvh, or a flexible min-height when mobile browser controls make 100vh an awkward fit.
- Making Links Easy to Recognize
Make links recognisable with underlines, clear focus states, useful text, and behaviour that does not surprise the reader.