Lesson 24 of 50
cssCSS Custom Properties (Variables)
9 mins
Course progress48%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 24 of 50
css9 mins
Keep these ideas in mind as you work through the lesson.
Custom properties (often called CSS variables) are first‑class citizens in the cascade. They inherit, can be changed at runtime, and even participate in calculations.
/* Define variables on :root (global scope) */
:root {
--primary:#0066cc;
--spacing:1rem;
--radius:4px;
}
/* Use them with var() */
.button { background:var(--primary); margin:var(--spacing); border-radius:var(--radius); }
document.documentElement.style.setProperty('--primary', '#ff6600');
The colour of every
.buttonupdates instantly – perfect for theme switches.
var(--unknown, #f00) returns #f00 if --unknown is not defined, preventing cascade errors.:root {
--bg:#fff; --text:#111; --primary:#0066cc;
}
[data-theme="dark"] {
--bg:#111; --text:#eee; --primary:#4a90e2;
}
body { background:var(--bg); color:var(--text); }
<button id="themeToggle">Toggle theme</button>
<script>
const btn = document.getElementById('themeToggle');
btn.addEventListener('click',()=>{
const root = document.documentElement;
root.dataset.theme = root.dataset.theme === 'dark' ? 'light' : 'dark';
});
</script>
:root for global availability..card { --card-bg:#fafafa; }).--color-primary, --spacing-md).calc(), clamp(), and min()/max() for fluid layouts.