CSS Variables (Custom Properties)
CSS Variables, also known as Custom
Properties, let you store values — like colors, fonts, or sizes — in reusable
variables. This makes your CSS more maintainable, consistent, and easier to
update across large projects.
Why
Use CSS Variables?
- Define a value once and reuse it multiple times.
- Easily update the design by changing the variable
value.
- Create themes by switching variable values dynamically.
- Improve code readability.
How
to Define and Use CSS Variables
CSS variables are declared inside a
selector (commonly :root
for global scope) using the syntax --variable-name:
value;
Example:
:root
{
--main-color: #3498db;
--font-size: 16px;
}
body
{
color: var(--main-color);
font-size: var(--font-size);
}
Key
Points
- Use the var() function to access the variable value.
- Variables can inherit and cascade like normal CSS
properties.
- You can provide fallback values: var(--variable, fallback).
- Variables can be updated dynamically with JavaScript.
Example:
Theming with CSS Variables
:root
{
--background: white;
--text-color: black;
}
.dark-theme
{
--background: #222;
--text-color: #eee;
}
body
{
background-color: var(--background);
color: var(--text-color);
}
Toggling the .dark-theme class on the body switches the color scheme easily.
CSS Variables empower you to write
cleaner, more flexible CSS and build adaptable designs without repetitive code.