css - CSS Variables
CSS variables, also called CSS custom properties, are a way to store reusable values in your CSS. They make your code cleaner, shorter, and easier to maintain, especially for colors, fonts, spacing, and responsive designs.
1. Defining CSS Variables
CSS variables are defined using the --variable-name
syntax and are usually placed inside the :root
selector for global scope.
:root {
--primary-color: #4caf50;
--secondary-color: #2196f3;
--font-size: 16px;
--padding: 10px;
}
Here:
-
:root
= the highest-level selector (similar tohtml
). -
Variables start with
--
. -
These variables can be reused anywhere in your CSS.
2. Using CSS Variables
To use a CSS variable, you apply the var()
function:
button {
background-color: var(--primary-color);
color: white;
font-size: var(--font-size);
padding: var(--padding);
border: none;
border-radius: 5px;
}
3. Local vs Global Variables
You can define variables globally or locally:
:root {
--main-color: #ff5722; /* Global */
}
.card {
--main-color: #009688; /* Local for this class only */
background-color: var(--main-color);
}
-
Inside
.card
, the local variable overrides the global one. -
Other elements still use the global
--main-color
.
4. Fallback Values
You can provide a default value if the variable is missing:
p {
color: var(--text-color, black);
}
-
If
--text-color
is not defined, it uses black.
5. CSS Variables with Media Queries
CSS variables make responsive design easier:
:root {
--font-size: 18px;
}
@media (max-width: 768px) {
:root {
--font-size: 14px;
}
}
p {
font-size: var(--font-size);
}
-
On desktop →
font-size: 18px
-
On mobile →
font-size: 14px
6. CSS Variables with JavaScript
You can update variables dynamically using JavaScript:
<button onclick="changeTheme()">Change Theme</button>
<script>
function changeTheme() {
document.documentElement.style.setProperty('--primary-color', '#ff9800');
}
</script>
:root {
--primary-color: #4caf50;
}
body {
background-color: var(--primary-color);
}
-
Clicking the button changes the entire site's theme instantly.
7. Practical Example: Theming with CSS Variables
<div class="container">
<h1>Welcome</h1>
<button>Click Me</button>
</div>
:root {
--bg-color: #ffffff;
--text-color: #333;
--btn-color: #4caf50;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
font-family: Arial, sans-serif;
}
button {
background-color: var(--btn-color);
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
}
To create a dark mode:
body.dark-mode {
--bg-color: #222;
--text-color: #fff;
--btn-color: #ff5722;
}
With JavaScript:
document.body.classList.toggle('dark-mode');
8. Advantages of CSS Variables
-
Easier maintenance and reusability.
-
Perfect for themes (light/dark).
-
Work natively in CSS without extra tools.
-
Can be updated dynamically with JS.