CSS Advanced Features

CSS Variables (Custom Properties)

CSS Variables (Custom Properties) are entities defined by CSS authors that contain specific values to be reused throughout a document, declared with -- prefix and accessed using var() function.

How do CSS variables (custom properties) work?

CSS variables store a value once and reuse it everywhere. Declare one with two dashes, --brand: #3b82f6; (usually on :root so it's global), and read it with var(--brand). Unlike Sass variables they're live: change them in a media query, a theme class or with JavaScript, and every use updates.

:root {
  --brand: #3b82f6;
  --space: 1rem;
}
.button {
  background: var(--brand);
  padding: var(--space) calc(var(--space) * 2);
}
[data-theme="dark"] { --brand: #60a5fa; }
.note { color: var(--accent, orange); }   /* fallback */

Interactive CSS Variables Demo

Code Editor

<div class="card">
  <h3>Themed card</h3>
  <button class="btn">Button</button>
</div>
<button id="theme">Toggle dark theme</button>

Preview

Defining CSS Variables

Basic Variable Definition

:root {
  /* Global variables available everywhere */
  --primary-color: #3b82f6;
  --secondary-color: #10b981;
  --font-size-base: 16px;
  --spacing-unit: 1rem;
}

/* Using variables */
.button {
  background-color: var(--primary-color);
  font-size: var(--font-size-base);
  padding: var(--spacing-unit);
}

Variables must start with -- and are case-sensitive. :root makes them globally available.

Local Variables

.card {
  --card-bg: #ffffff;
  --card-shadow: 0 2px 4px rgba(0,0,0,0.1);
  background: var(--card-bg);
  box-shadow: var(--card-shadow);
}

.card.dark {
  --card-bg: #1f2937;
  --card-shadow: 0 2px 4px rgba(0,0,0,0.3);
}

Variables can be scoped to specific elements

Fallback Values

.element {
  /* Single fallback */
  color: var(--text-color, #333333);
  
  /* Multiple fallbacks */
  font-family: var(
    --custom-font,
    var(--system-font, sans-serif)
  );
}

Provide fallback values for undefined variables

Variable Inheritance & Scope

Variable Inheritance

.parent {
  --text-color: #333333;
  --spacing: 1rem;
}

.child {
  /* Inherits parent variables */
  color: var(--text-color);
  margin: var(--spacing);
  
  /* Override for this scope */
  --text-color: #666666;
}

.grandchild {
  /* Uses child's overridden value */
  color: var(--text-color); /* #666666 */
}

Variables inherit down the DOM tree and can be overridden at any level.

Media Query Variables

:root {
  --font-size: 16px;
  --container-width: 1200px;
}

@media (max-width: 768px) {
  :root {
    --font-size: 14px;
    --container-width: 100%;
  }
}

.container {
  max-width: var(--container-width);
  font-size: var(--font-size);
}

Responsive variables that change with screen size

Theme Variables

/* Light theme (default) */
:root {
  --bg-color: #ffffff;
  --text-color: #1f2937;
  --border-color: #e5e7eb;
}

/* Dark theme */
[data-theme="dark"] {
  --bg-color: #1f2937;
  --text-color: #f9fafb;
  --border-color: #374151;
}

body {
  background: var(--bg-color);
  color: var(--text-color);
}

Theme switching with variable overrides

JavaScript Integration

Dynamic Variable Updates

// Get variable value
const root = document.documentElement;
const primaryColor = getComputedStyle(root)
  .getPropertyValue('--primary-color');

// Set variable value
root.style.setProperty('--primary-color', '#ef4444');

// Remove variable
root.style.removeProperty('--primary-color');

// Bulk update variables
const theme = {
  '--primary-color': '#3b82f6',
  '--secondary-color': '#10b981',
  '--font-size': '18px'
};

Object.entries(theme).forEach(([prop, value]) => {
  root.style.setProperty(prop, value);
});

JavaScript can read and modify CSS variables in real-time.

Interactive Controls

// Color picker integration
const colorPicker = document.getElementById('color');
colorPicker.addEventListener('input', (e) => {
  document.documentElement
    .style.setProperty('--accent-color', e.target.value);
});

// Range slider for spacing
const spacingSlider = document.getElementById('spacing');
spacingSlider.addEventListener('input', (e) => {
  const value = e.target.value + 'px';
  document.documentElement
    .style.setProperty('--base-spacing', value);
});

Create interactive theme customizers

Animation with Variables

.animated-element {
  background: var(--bg-color);
  transition: background 0.3s ease;
}

// Smooth color transitions
function animateToColor(newColor) {
  document.documentElement
    .style.setProperty('--bg-color', newColor);
}

// Animate with CSS keyframes
@keyframes colorShift {
  0% { --hue: 0; }
  100% { --hue: 360; }
}

Smooth animations using variable changes

Best Practices & Common Patterns

Design System Variables

:root {
  /* Color Palette */
  --color-primary-50: #eff6ff;
  --color-primary-500: #3b82f6;
  --color-primary-900: #1e3a8a;

  /* Spacing Scale */
  --space-xs: 0.25rem;
  --space-sm: 0.5rem;
  --space-md: 1rem;
  --space-lg: 1.5rem;
  --space-xl: 3rem;

  /* Typography Scale */
  --text-xs: 0.75rem;
  --text-sm: 0.875rem;
  --text-base: 1rem;
  --text-lg: 1.125rem;
  --text-xl: 1.25rem;

  /* Shadows */
  --shadow-sm: 0 1px 2px 0 rgba(0,0,0,0.05);
  --shadow-md: 0 4px 6px -1px rgba(0,0,0,0.1);
  --shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.1);
}

Organize variables into systematic scales for consistent design.

Best Practices

  • • Use semantic naming conventions
  • • Group related variables together
  • • Provide fallback values for browser compatibility
  • • Use calc() with variables for dynamic calculations
  • • Document your variable system
  • • Test variable inheritance thoroughly

Advanced Tips

  • • Use variables in calc() expressions
  • • Create component-specific variable scopes
  • • Combine with CSS Grid for responsive layouts
  • • Use for consistent animation timings
  • • Create toggle variables for conditional styles
  • • Use with CSS-in-JS libraries

CSS Variables — step by step

1 / 4
1

Declaring Custom Properties

Define variables on :root with double dashes: --primary: #3b82f6. They cascade like any CSS property and are accessible in all descendant elements.

1 of 4
💡Variables Cascade — Scope Them to Components
CSS custom properties follow the cascade. Define global tokens on :root and override them on component selectors to create self-contained themes without breaking other parts of the page.

🎯 Quick Check

What is the correct syntax to declare a CSS custom property?

CSS Variables: summary

Key points

  • Custom properties inherit, so setting one on a component overrides it for everything inside.
  • The second argument of var() is a fallback used when the variable isn't defined.
  • JavaScript can read and set them: el.style.setProperty('--brand', 'red').
  • Variable names are case-sensitive: --Brand and --brand are different.

Frequently asked questions

›What is the difference between CSS variables and Sass variables?

Sass variables are replaced with fixed values at build time. CSS variables exist in the browser, follow the cascade, and can change at runtime, which is ideal for themes and dark mode.

›How do I make a dark mode with CSS variables?

Define colour variables on :root, then redefine them inside @media (prefers-color-scheme: dark) or a [data-theme="dark"] selector. Every component that uses var() switches automatically.