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
CSS Box Model
Web DevelopmentVisualize content, padding, border, and margin layers with an interactive box model explorer.
JSON & APIs
Web DevelopmentLearn JSON syntax, parse and build data structures, and explore how REST APIs work interactively.
Responsive Design & Media Queries
Web DevelopmentBuild layouts that adapt to any screen size using media queries, fluid grids, and responsive units.