35 Mins intermediate
14. CSS Variables & Custom Properties
CSS Architecture
CSS Variables
Imagine needing to change your brand color across 200 CSS files. Without variables, you'd manually find and replace every instance. CSS Custom Properties (variables) solve this — define a color once, use it everywhere, and changing one line updates the whole site.
🎨 Defining & Using Variables
<style>
:root {
--primary: #00A3FF;
--secondary: #C792EA;
--text: #333;
--bg: #f8f9fa;
--radius: 8px;
--spacing: 16px;
}
body { background: var(--bg); font-family: sans-serif; color: var(--text); padding: var(--spacing); }
.btn-primary { background: var(--primary); color: white; padding: 10px 20px; border: none; border-radius: var(--radius); cursor: pointer; font-weight: bold; }
.btn-secondary { background: var(--secondary); color: white; padding: 10px 20px; border: none; border-radius: var(--radius); cursor: pointer; font-weight: bold; }
h2 { color: var(--primary); }
</style>
<h2>CSS Variables Demo</h2>
<p>All colors, spacing, and borders come from CSS variables defined in :root.</p>
<button class="btn-primary">Primary Button</button>
<button class="btn-secondary" style="margin-left: 8px;">Secondary Button</button>
🌙 Dark Mode with Variables
<style>
:root { --bg: white; --text: #333; --card-bg: #f0f0f0; }
[data-theme="dark"] { --bg: #1a1a2e; --text: #eee; --card-bg: #2d2d44; }
body { background: var(--bg); color: var(--text); font-family: sans-serif; padding: 20px; transition: all 0.3s; }
.card { background: var(--card-bg); padding: 20px; border-radius: 8px; }
button { padding: 8px 16px; cursor: pointer; border: none; border-radius: 4px; font-weight: bold; }
</style>
<div id="page">
<div class="card">
<h3>Theme Switcher</h3>
<p>Click the button to toggle dark mode. Notice how variables update everything at once.</p>
<button onclick="document.getElementById('page').toggleAttribute('data-theme') || document.getElementById('page').setAttribute('data-theme','dark'); this.closest('[data-theme]') ? document.getElementById('page').setAttribute('data-theme','dark') : document.getElementById('page').removeAttribute('data-theme')">Toggle Dark Mode</button>
</div>
</div>
<script>
document.querySelector('button').onclick = () => {
const el = document.getElementById('page');
el.dataset.theme = el.dataset.theme === 'dark' ? '' : 'dark';
};
</script>
Knowledge Check
Ready to test your understanding of 14. CSS Variables & Custom Properties?