CSS Variables (Custom Properties)
Define your colours and sizes once, reuse them everywhere, and theme your whole site by changing a few lines.
What you will learn
- Define and use custom properties
- Centralise your design tokens
- Build a quick theme switch
Define once, use everywhere
Declare variables on :root (the whole document) with a --name, and use them with var(--name). Change the variable once and every use updates.
<style>
:root {
--brand: #4338ca;
--accent: #06b6d4;
--radius: 12px;
}
.btn { background: var(--brand); color:#fff; border:none; padding:12px 20px;
border-radius: var(--radius); cursor:pointer; }
.card { border:2px solid var(--accent); border-radius: var(--radius); padding:16px; margin-top:12px; }
</style>
<button class="btn">Brand button</button>
<div class="card">Accent card — both share the same variables.</div>CSS variables work in two moves. First you define them on :root (which means “the whole document”): --brand, --accent and --radius are just named storage for values. The double-dash -- is what marks a custom property. Then you use them with var(...): the button reads var(--brand) for its colour and var(--radius) for its corners, and the card reuses var(--accent) and the same var(--radius). The payoff: change --brand in that one :root block and every element using it updates at once — perfect for theming a whole site from a few lines.
Tip: This is exactly how this app is themed — the brand colours live in :root variables, so rebranding means changing a handful of lines. Real design systems work this way.
Note: Unlike old preprocessor variables, CSS custom properties are live in the browser and can even be changed with JavaScript — perfect for dark-mode toggles and theming.
Q. How do you USE a CSS variable named --brand?
✍️ Practice
- Define
--brandand--radiusvariables and use them across several elements. - Change one variable value and watch every element that uses it update.
🏠 Homework
- Refactor your project’s CSS to use variables for all your main colours and the corner radius.