What are CSS Variables?
CSS Variables, also known as Custom Properties, allow you to store values (like colors, sizes, fonts, etc.) in a variable and reuse them throughout your stylesheet.
They make your CSS cleaner, reusable, and easier to maintain.
Syntax
Declare a variable
You declare a variable using the syntax --variable-name: value;
:root {
--main-color: #3498db;
--padding-size: 16px;
}
:root
selector targets the highest-level element (html tag)- Variables declared in
:root
are global, accessible anywhere
Use a variable
To use the variable, wrap it inside the var()
function
button {
background-color: var(--main-color);
padding: var(--padding-size);
}
Example
:root {
--primary-color: #ff6600;
--font-size: 18px;
--margin-space: 20px;
}
h1 {
color: var(--primary-color);
font-size: var(--font-size);
margin-bottom: var(--margin-space);
}
This lets you manage all your key design values from one place.
Local Scope
You can also define variables inside a specific selector, making them local to that element.
.card {
--text-color: #333;
color: var(--text-color);
}
This variable is only accessible within .card
and its children.
Fallback Values
If a variable is not defined, you can provide a fallback value.
h2 {
color: var(--undefined-color, blue);
}
If --undefined-color
is missing, blue
will be used.
Why Use CSS Variables?
- Reusable: Write once, use multiple times
- Maintainable: Change in one place updates everywhere
- Responsive: Can work with media queries
- Theming: Easily switch themes by changing variable values
Changing CSS Variables Dynamically with JavaScript
CSS variables can be changed using JavaScript for dynamic styling
document.documentElement.style.setProperty('--main-color', '#e74c3c');
This updates the variable --main-color
at runtime
Summary
- CSS Variables use
--
to define andvar()
to use - Declared globally with
:root
or locally in specific selectors - Support fallback values and JavaScript updates
- Make CSS scalable, clean, and easy to manage