QA
Beginner LevelCSS & Modern Layouts

How do CSS Custom Properties (CSS Variables) work?

❓ Interview Prompt: Explain declaration, inheritance, fallback values, and runtime modification of CSS variables.

CSS Custom Properties (variables) store reusable values that cascade and inherit through the DOM tree.

Declaration:

Defined with -- prefix, typically on :root for global scope: :root { --color-primary: #3d2c2e; }

Usage:

Accessed via the var() function: color: var(--color-primary);

Key Features:

•
Inheritance: Children inherit parent variables unlike preprocessor variables (Sass $variables compile away).
•
Fallback values: var(--color-accent, #886f68) uses #886f68 if the variable is undefined.
•
Runtime updates: Can be changed via JavaScript: element.style.setProperty('--color-primary', 'blue').
•
Scoped overrides: Redeclare on any selector to override within a subtree.

Code Implementation Example

css
:root {
  --bg-main: #f5edf0;
  --text-main: #3d2c2e;
  --text-muted: #886f68;
  --radius: 8px;
}

.card {
  background: var(--bg-main);
  color: var(--text-main);
  border-radius: var(--radius);
}

/* Scoped override for dark sections */
.dark-section {
  --bg-main: #3d2c2e;
  --text-main: #f5edf0;
}
💡Global CSS variables with scoped dark-section override.
🎯 Interview Key Takeaway

CSS variables cascade and inherit through the DOM, enabling runtime theme switching without JavaScript frameworks.

#Variables#Custom Properties#Theming#Beginner
Back to all CSS & Modern Layouts Questions→

More CSS & Modern Layouts Interview Questions

Beginner LevelCSS & Modern Layouts

What is the CSS Box Model and how do content, padding, border, and margin interact?

Beginner LevelCSS & Modern Layouts

How does CSS specificity and the cascade determine which styles are applied?

Beginner LevelCSS & Modern Layouts

What are the differences between display: block, inline, inline-block, flex, and grid?