Welcome to Part 11 of the CSS Mastery & Responsive Layouts Course. In this part, we will explore CSS Variables (Custom Properties) & Cascading.
CSS custom properties, commonly known as CSS variables, allow you to store design tokens (like colors, spacing values, font families, and sizes) in one place and reuse them throughout your stylesheet. Unlike preprocessor variables (like SCSS/Sass variables), native CSS variables are dynamic: they exist at runtime in the browser, cascade according to standard selector rules, and can be read or modified dynamically using JavaScript.
Chapter 77: Declaring & Consuming Custom Properties
Custom property names must start with double hyphens (--). They are case-sensitive.
77.1 Declaration Syntax
You declare variables inside a CSS declaration block:
.card {
--card-bg: #ffffff;
--card-padding: 1.5rem;
}
77.2 Consumption Syntax (var())
You retrieve the value of a custom property using the var() function:
.card {
background-color: var(--card-bg);
padding: var(--card-padding);
}
77.3 Fallback Values
You can specify a fallback value that applies if the custom property is not defined or invalid:
.card-title {
/* Falls back to black if --title-color is undefined */
color: var(--title-color, black);
}
/* Nested Fallbacks */
.card-text {
color: var(--text-color, var(--fallback-color, #333));
}
Chapter 78: Variable Scopes: Global vs. Local
Like programming languages, CSS variables have scopes determined by the selectors they are declared in.
78.1 Global Scope (:root)
Declaring variables inside the :root pseudo-class (which matches the <html> root node) makes them available globally across the entire webpage:
:root {
--primary-color: #3b82f6;
--base-spacing: 8px;
}
78.2 Local Scope
Declaring variables inside a specific selector limits their scope to that element and its nested children:
.btn-accent {
--btn-bg: #ef4444; /* Local scope */
background-color: var(--btn-bg);
}
/* This will fail to render red, as --btn-bg is not in scope here */
.footer {
background-color: var(--btn-bg);
}
Chapter 79: Custom Properties Cascading & Overrides
Custom properties follow the standard CSS cascade and inheritance algorithms.
79.1 Inheritance
A child element inherits custom properties declared on its parent.
79.2 Dynamic Overrides
You can redefine variable values on specific elements or conditions (like hover states or media queries) without writing new declarations for other properties:
:root {
--padding: 20px;
}
/* Redefine padding on larger screens */
@media (min-width: 768px) {
:root {
--padding: 40px; /* All components using var(--padding) scale automatically */
}
}
.box {
padding: var(--padding);
}
Chapter 80: Dynamic Manipulation via JavaScript
Because custom properties exist at runtime in the browser DOM, you can read and write them dynamically using JavaScript.
80.1 Setting Variable Values
Use element.style.setProperty() to change a variable value:
// Change theme color on root element
document.documentElement.style.setProperty('--primary-color', '#10b981');
80.2 Reading Variable Values
Use getComputedStyle() to read a variable value resolved by the browser:
const styles = getComputedStyle(document.documentElement);
const themeColor = styles.getPropertyValue('--primary-color').trim();
console.log(themeColor); // Output: #10b981
Chapter 81: Custom Properties Practice & Self-Check
81.1 Practice Exercises
- Exercise 1: Light/Dark Theme Switcher: Create a CSS variable theme layout toggled by a
.dark-themeclass::root { --bg-color: #ffffff; --text-color: #1e293b; } .dark-theme { --bg-color: #0f172a; --text-color: #f1f5f9; } body { background-color: var(--bg-color); color: var(--text-color); transition: background-color 0.3s ease; } - Exercise 2: Button Hover Modification: Override button colors on hover using only variable updates.
.btn-action { --color: #3b82f6; background-color: var(--color); color: white; } .btn-action:hover { --color: #2563eb; /* Clean override */ }
81.2 Self-Check Questions
- What characters must custom properties start with?
- Answer: Double hyphens (
--).
- Answer: Double hyphens (
- Are CSS variables case-sensitive?
- Answer: Yes,
--primary-colorand--Primary-Colorare treated as separate variables.
- Answer: Yes,
- What pseudo-class is typically used to declare global variables?
- Answer:
:root.
- Answer:
- What happens if a consumed variable is undefined and no fallback is specified?
- Answer: The browser treats the property as invalid at computed-value time, falling back to
unset.
- Answer: The browser treats the property as invalid at computed-value time, falling back to
- How do you read a custom property value resolved by the browser in JavaScript?
- Answer: Use
getComputedStyle(element).getPropertyValue('--variable-name').
- Answer: Use
- Can custom properties inherit?
- Answer: Yes, custom properties inherit from parent to child by default.
- What is the difference between Sass variables ($color) and CSS variables (—color)?
- Answer: Sass variables are compiled away to static values at build time; CSS variables exist at runtime in the browser DOM and can adapt dynamically.
- Why is it useful to override variables in media queries?
- Answer: It allows responsive layout values to scale globally without duplicating element selectors.
- What method is used to modify a variable’s value on an element style block in JS?
- Answer:
element.style.setProperty('--variable-name', 'value').
- Answer:
- Can you use variables inside the var() function fallback parameter?
- Answer: Yes, nested fallbacks are valid (e.g.
var(--a, var(--b))).
- Answer: Yes, nested fallbacks are valid (e.g.
Discussion
Loading comments...