CSS Variables & Custom Properties
Learn CSS custom properties — define, inherit, override, and dynamically update variables for theming.
Step 1: What are CSS Variables?
CSS Custom Properties (commonly called CSS variables) let you store values in one place and reuse them throughout your stylesheet. They make your CSS more maintainable, readable, and dynamic.
A custom property is declared with a double-hyphen prefix (--) and accessed with the var() function:
:root {
--primary-color: #3b82f6;
--font-size: 16px;
--spacing: 1rem;
}
.button {
background: var(--primary-color);
font-size: var(--font-size);
padding: var(--spacing);
}
You can also provide a fallback value in case the variable is not defined:
color: var(--accent-color, #e74c3c);
Key terms:
- Custom property — a property name starting with
--, e.g.--my-color - var() — the function used to retrieve a custom property's value
- :root — the top-level selector (the
<html>element), used for global variables - Fallback value — a default passed as the second argument to
var() - Scope — variables are inherited by descendant elements and can be overridden at any level
About This Lab
How It Works
- 1 Read each step's explanation of CSS variable concepts
- 2 Modify variables and see styles update instantly
- 3 Build a theme switcher from scratch
- 4 Experiment with scope and inheritance
- 5 Complete the quiz to test your understanding
More Labs in Web Development
Color Theory for Developers
Web DevelopmentUnderstand RGB, HSL, and hex colors — build palettes and explore contrast with interactive pickers.
HTML Forms & Validation
Web DevelopmentBuild forms with various input types and learn client-side validation with HTML5 and JavaScript.
CSS Animations & Transitions
Web DevelopmentMaster CSS transitions, keyframe animations, and timing functions with hands-on interactive examples.