How to Use CSS Variables: Simple Guide with Examples
Use
--variable-name to define a CSS variable inside a selector, usually :root. Access it with var(--variable-name) anywhere in your CSS to reuse the value.Syntax
CSS variables are defined with a name starting with two dashes -- inside a selector. The :root selector is commonly used to make variables global. Use var(--variable-name) to get the value of the variable.
- --variable-name: The name of the variable.
- :root: The global scope for variables.
- var(): Function to use the variable value.
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 to style text color and padding. Changing the variable in :root updates all uses automatically.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>CSS Variable Example</title> <style> :root { --main-color: #e67e22; --padding: 1.5rem; } body { font-family: Arial, sans-serif; } .box { background-color: var(--main-color); padding: var(--padding); color: white; border-radius: 0.5rem; max-width: 300px; margin: 2rem auto; text-align: center; } </style> </head> <body> <div class="box">This box uses CSS variables for color and padding.</div> </body> </html>
Output
A centered orange box with white text and rounded corners, padded inside with space around the text.
Common Pitfalls
Common mistakes include:
- Defining variables outside a selector or without
--prefix. - Using
var()with a wrong variable name or missing fallback. - Not using
:rootfor global variables, causing scope issues.
Always check variable names and scopes carefully.
css
:root {
--main-color: #2ecc71;
}
/* Wrong: missing -- prefix */
.element {
color: var(main-color); /* This will not work */
}
/* Correct: with -- prefix */
.element {
color: var(--main-color, black); /* fallback black if variable missing */
}Quick Reference
| Concept | Usage | Notes |
|---|---|---|
| Define variable | :root { --name: value; } | Global scope for variables |
| Use variable | property: var(--name); | Insert variable value |
| Fallback value | var(--name, fallback) | Used if variable is not defined |
| Variable name | Must start with -- | Example: --main-color |
| Scope | Variables can be local to selectors | Use :root for global |
Key Takeaways
Define CSS variables with --name inside a selector, usually :root for global use.
Use var(--name) to access the variable value anywhere in your CSS.
Always include the -- prefix in variable names and check spelling carefully.
Use fallback values in var() to avoid errors if a variable is missing.
CSS variables help keep styles consistent and easy to update.