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 Grid Layout
Web DevelopmentBuild two-dimensional layouts with CSS Grid — define rows, columns, and place items with interactive controls.
Intro to HTML
Web DevelopmentLearn the building blocks of the web — write your first HTML elements and see them render in real time.
CSS Animations & Transitions
Web DevelopmentMaster CSS transitions, keyframe animations, and timing functions with hands-on interactive examples.