CSS Variables (Custom Properties)
Reusable, dynamic, and powerful: Master CSS custom properties with hands-on examples!
What Are CSS Variables?
CSS variables (also called custom properties) allow you to store values in reusable variables directly in your CSS. They make your stylesheets more maintainable, flexible, and dynamic.
Syntax: --variable-name: value; and usage: var(--variable-name).
- Global Scope: Define variables in
:rootto make them available everywhere. - Local Scope: Define variables inside a selector to limit their use to that element and its children.
- Dynamic Updates: Variables can be changed at runtime using JavaScript or by changing classes.
- Inheritance: CSS variables inherit like other CSS properties.
Example 1: Global Variables
:root {
--main-bg: #f0f4ff;
--accent: #3498db;
--radius: 12px;
}
.box {
background: var(--main-bg);
border: 2px solid var(--accent);
border-radius: var(--radius);
color: var(--accent);
padding: 1rem 2rem;
font-weight: bold;
}
This box uses global CSS variables!
How CSS Variables Work
- Declaration: Use
--name: value;inside a selector. The--prefix is required. - Usage: Use
var(--name)wherever a value is expected. The browser replaces this with the variable's value. - Fallbacks:
var(--name, fallback)provides a default value if the custom property is not defined. This is great for robustness. - Inheritance: Variables inherit down the DOM tree. If you set a variable on a parent, it's available to all its children, unless overridden.
- Case-Sensitive: Variable names like
--my-colorand--My-Colorare treated as different variables.
Example 2: Local Scope & Overriding
/* A default theme variable */
:root {
--theme-bg: #f0f0f0;
--theme-text: #333;
}
.theme-light {
--theme-bg: #fff;
--theme-text: #222;
}
.theme-dark {
--theme-bg: #222;
--theme-text: #fff;
}
.card {
background: var(--theme-bg);
color: var(--theme-text);
padding: 1rem 2rem;
border-radius: 8px;
margin-bottom: 1rem;
}
Default Theme
Light Theme Card
Dark Theme Card
Best Practices & Tips
- Use
:rootfor global, site-wide variables (e.g., brand colors, spacing units, font families). - Define component-level variables for properties that only affect a single component, enhancing encapsulation.
- Leverage variables for easy theming (like light/dark mode) by redefining them within a class or media query.
- Combine with
calc()for dynamic calculations, likewidth: calc(100% - var(--spacing-large));. - Remember: CSS variables are not supported in IE11 and below. For modern projects, this is rarely an issue.
Example 3: Fallback Values
.fallback-demo {
/* --not-set is not defined */
color: var(--not-set, #e74c3c);
font-size: 1.2rem;
padding: 0.5rem 1rem;
border: 1px dashed var(--not-set, #e74c3c);
border-radius: 6px;
}
This uses a fallback color because
--not-set is not defined.