How to Use var() in CSS: Simple Guide with Examples
In CSS, you use
var(--variable-name) to access a custom property (variable) defined with --variable-name. Define variables inside a selector like :root for global use, then call them with var() wherever needed.Syntax
CSS variables are custom properties defined with two dashes -- followed by a name. You use var(--variable-name) to get the value of that variable.
- --variable-name: The name of your custom property.
- var(--variable-name): The function to use the variable's value.
- :root: A special selector for global variables.
css
:root {
--main-color: #3498db;
--padding: 1rem;
}
.element {
color: var(--main-color);
padding: var(--padding);
}Example
This example shows how to define CSS variables globally and use them in styles. The text color and padding come from variables, making it easy to change the look by editing only the variables.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>CSS var() Example</title> <style> :root { --main-bg-color: #f0f8ff; --text-color: #2c3e50; --spacing: 2rem; } body { background-color: var(--main-bg-color); color: var(--text-color); padding: var(--spacing); font-family: Arial, sans-serif; } h1 { margin-bottom: var(--spacing); } </style> </head> <body> <h1>Using CSS Variables with var()</h1> <p>This text uses colors and spacing from CSS variables.</p> </body> </html>
Output
A webpage with a light blue background, dark blue text, and generous padding around the content. The heading and paragraph use the colors and spacing defined by CSS variables.
Common Pitfalls
Common mistakes when using var() include:
- Forgetting to define the variable before using it.
- Using incorrect variable names or missing the
--prefix. - Not providing a fallback value, which can cause styles to break if the variable is missing.
Always define variables in a scope accessible to where you use them, and consider fallback values like var(--color, black).
css
/* Wrong: variable not defined */ .element { color: var(--undefined-color); } /* Right: variable defined with fallback */ :root { --defined-color: blue; } .element { color: var(--defined-color, black); }
Quick Reference
- Define variables: Use
--name: value;inside a selector. - Use variables: Call with
var(--name). - Global scope: Use
:rootselector for variables used everywhere. - Fallback values: Use
var(--name, fallback)to avoid errors.
Key Takeaways
Define CSS variables with --name inside a selector like :root for global use.
Use var(--name) to access the variable's value in your styles.
Always include fallback values in var() to prevent broken styles if a variable is missing.
CSS variables make it easy to update colors, spacing, and other values in one place.
Variable names must start with two dashes and be spelled exactly when used.