How to Create CSS Variables: Simple Syntax and Examples
To create a CSS variable, define it inside a selector using
--variable-name: value;. Then use it with var(--variable-name) anywhere in your CSS to reuse the value.Syntax
CSS variables are created by defining a custom property inside a selector, usually :root for global scope. The name starts with two dashes --, followed by the variable name and a value. You use the variable with the var() function.
- --variable-name: The name of your variable, must start with two dashes.
- value: Any valid CSS value like colors, sizes, fonts.
- var(--variable-name): Use this to insert the variable's value.
css
:root {
--main-color: #3498db;
--padding: 1rem;
}
.element {
color: var(--main-color);
padding: var(--padding);
}Example
This example shows how to create CSS variables for colors and padding, then use them to style a box. Changing the variable value updates all uses automatically.
css
html {
font-family: Arial, sans-serif;
}
:root {
--box-bg-color: #f39c12;
--box-padding: 2rem;
--box-border-radius: 10px;
}
.box {
background-color: var(--box-bg-color);
padding: var(--box-padding);
border-radius: var(--box-border-radius);
color: white;
width: 200px;
text-align: center;
margin: 2rem auto;
font-weight: bold;
}Output
A centered orange box with white text, rounded corners, and padding inside.
Common Pitfalls
Common mistakes when using CSS variables include:
- Not prefixing variable names with
--. - Trying to use variables outside their scope (e.g., defined inside a selector but used elsewhere).
- Forgetting to use
var()when referencing variables. - Using variables in unsupported CSS properties or older browsers without fallback.
Always define variables in :root for global use or inside specific selectors for local use.
css
:root {
/* Correct variable definition */
--primary-color: blue;
}
/* Wrong: missing -- prefix */
:root {
primary-color: blue; /* This won't work */
}
.element {
/* Wrong: missing var() function */
color: --primary-color; /* This won't work */
/* Correct usage */
color: var(--primary-color);
}Quick Reference
Remember these quick tips for CSS variables:
- Define variables with
--name: value;inside a selector. - Use variables with
var(--name). - Use
:rootfor global variables. - Variables cascade and inherit like normal CSS properties.
- You can provide fallback values:
var(--name, fallback).
Key Takeaways
Create CSS variables by defining custom properties with --name inside selectors.
Use variables anywhere in CSS with var(--name) to reuse values easily.
Define variables in :root for global access across your styles.
Always prefix variable names with -- and use var() to reference them.
CSS variables help keep styles consistent and easy to update.