element { /* Local scope (element only) */
--local-variable: value;
}
/* =================================== USING VARIABLES
=================================== */ element {
property: var(--variable-name);
property: var(--variable-name,
fallback-value);
}
/* =================================== COMMON VARIABLE NAMES
=================================== */ --color-primary: #007bff;
--color-secondary: #6c757d;
--color-success: #28a745;
--color-danger: #dc3545;
--color-warning: #ffc107;
--color-info: #17a2b8;
--color-light: #f8f9fa;
--color-dark: #343a40;
--spacing-unit: 8px;
--border-radius: 4px;
--transition-speed: 0.3s;
--font-family-base: 'Inter', sans-serif;
/* =================================== BENEFITS OF CSS VARIABLES
=================================== */ 1. Maintainability - Change one
value, update everywhere
2. Theming - Easily switch between light/dark mode
3. Consistency - Use same values across entire site
4. Dynamic - Can be changed with JavaScript
5. Responsive - Change values at different breakpoints
🧠 Quick Quiz
/* Question 1: How do you define a CSS variable? */ /* Answer:
--variable-name: value; */ /* Question 2: How do you use a CSS
variable? */ /* Answer: property: var(--variable-name); */ /* Question
3: Where do you define global variables? */ /* Answer: :root { } */ /*
Question 4: What happens when a variable is not defined? */ /* Answer:
The property is ignored (unless you provide a fallback) */ /* Question
5: Can CSS variables be changed with JavaScript? */ /* Answer: Yes!
document.body.style.setProperty('--color-primary', 'red'); */