agyanadda@gmail.com

CSS Variables

Advanced CSS 1 min read Updated Dec 1, 2026 Topic 32 of 39

CSS variables store values you reuse, like brand colours.

Declare

:root {
  --primary: #1f386b;
  --radius: 8px;
}

Variable names start with two dashes. :root makes them available everywhere.

Use

background: var(--primary);

Fallback

color: var(--text, #333); uses #333 if --text is not defined.

Theming

Change a variable in one place (or inside a class like .dark) and every rule that uses it updates.

Example

Example — Theme with variables HTML
<style>
  :root { --bg: #ffffff; --text: #222; --primary: #1f386b; }
  .dark { --bg: #1e1e1e; --text: #eee; --primary: #4a90e2; }
  .panel { background: var(--bg); color: var(--text); padding: 16px; border: 2px solid var(--primary); border-radius: 8px; margin-bottom: 10px; }
  .panel h3 { color: var(--primary); margin-top: 0; }
</style>

<div class="panel"><h3>Light theme</h3>Same CSS rules.</div>
<div class="panel dark"><h3>Dark theme</h3>Only the variables changed.</div>

Test Yourself With Exercises

Exercise 1 Multiple Choice

How do you use a variable named --main?

Exercise 2 Fill in the Blank

Global variables are usually declared in the :___ selector.

Exercise 3 True / False

CSS variable names start with two dashes.

Frequently Asked Questions

Yes: document.documentElement.style.setProperty('--primary', 'red');