CSS Variables
What are CSS Variables?
CSS Variables (Custom Properties) let you store values and reuse them throughout your stylesheet. They make maintaining and theming your CSS much easier!
Defining Variables
Define variables with --variable-name and use them with
var(--variable-name). Define global variables in
:root.
Fallback Values
Provide fallback values in case a variable isn't defined:
var(--variable, fallback).
Variable Scope
Variables are scoped to the element they're defined on and its children. Override global variables locally!
Color Themes
Use variables to create switchable themes. Perfect for light/dark mode!
Calculations with Variables
Use variables in calc() for dynamic
calculations.
Design System with Variables
Create a complete design system using CSS variables for colors, spacing, and typography.
:root for easy maintenance and
theming.
Summary
- Define:
--variable-name: value; - Use:
var(--variable-name) - Fallback:
var(--variable, fallback) - Global scope: Define in
:root - Local scope: Override in specific elements
- Perfect for themes, design systems, and maintainability
Quick Quiz
Where should you define global CSS variables?
Enjoying these tutorials?