Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

CSS Custom Properties (Varia | CSS Basics to Advanced lesson | BraveProgrammer
  1. Courses
  2. /
  3. CSS Basics to Advanced

Lesson 24 of 50

·css

CSS Custom Properties (Variables)

9 mins

Course progress48%

What you'll learn

Keep these ideas in mind as you work through the lesson.

3 points
  • Custom properties are **inherited**, so you can define a theme at `:root` and override locally.
  • They work inside `calc()`, `var()` can have a fallback value (`var(--missing, #f00)`).
  • Enable **runtime theming** without recompiling CSS.

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.

Declaration & Usage

/* 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); }

Runtime Updating via JavaScript

document.documentElement.style.setProperty('--primary', '#ff6600');

The colour of every .button updates instantly – perfect for theme switches.


Fallback Values

var(--unknown, #f00) returns #f00 if --unknown is not defined, preventing cascade errors.

Example – Dark‑Mode Toggle with CSS Variables

: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>

Best Practice Checklist

  • Declare most variables on :root for global availability.
  • Scope variables to a component when they are not part of the design system (.card { --card-bg:#fafafa; }).
  • Keep naming semantic (--color-primary, --spacing-md).
  • Use variables inside calc(), clamp(), and min()/max() for fluid layouts.
Make it stickPractice what you've learned1 quiz · 6 practical tests · Optional activities from CSS Basics to AdvancedBrowse activities
Previous lessonResponsive Design – Media QueriesContinue to lesson 25CSS Functions – calc(), clamp(), min(), max()Back to CSS Basics to Advanced curriculum