VITSOLS
2025-10-07
What are CSS Variables?
CSS Variables let you store values (like colors, font sizes, margins) and reuse them throughout your styles. They are defined using two dashes -- and accessed using the var() function.
Example:
CSS
:root {
--primary-color: #3498db;
--font-size-large: 20px;
}
HTML
h1 {
color: var(--primary-color);
font-size: var(--font-size-large);
}
👉 Here, --primary-color and --font-size-large are CSS variables.
Global vs Local Scope in CSS Variables
1. Global Variables
- Declared inside the :root selector (the top-level element of a page).
- Accessible anywhere in the CSS file.
Example:
:root {
--main-bg: #ffffff;
--main-text: #333333;
}
2. Local Variables
- Declared inside a specific selector.
- Available only within that selector (or its children).
Example:
.card {
--card-bg : #f5f5f5;
background: var(--card-bg);
padding: 20px;
}
.button {
background: var(--card-bg); /* ❌ Won’t work here */
}
👉 In this case, --card-bg works only inside .card, not outside.
How var() Function Works
The var() function retrieves the value of a CSS variable.
It can also take a fallback value if the variable is not defined.
Example:
CSS
body {
color: var(--text-color, black); /* fallback: black */
}
👉 Here, if --text-color is not defined, it will use black as the text color.
Why Use CSS Variables? (Real-Time Benefits)
- ✅ Easy Maintenance – Change once in :root, and it updates everywhere.
- ✅ Theming Support – Build light/dark themes with just variable swaps.
- ✅ Consistency – Maintain the same design system across pages.
- ✅ Responsive Design – Adjust spacing, font sizes, or breakpoints dynamically.
- ✅ Reusability – Use the same variable in multiple components.
Real-Time Use Cases
1. Light and Dark Mode
CSS
:root {
--bg-color: #ffffff;
--text-color: #000000;
}
.dark-theme {
--bg-color: #000000;
--text-color: #ffffff;
}
HTML
body {
background: var(--bg-color);
color: var(--text-color);
}
2. Consistent Spacing
CSS
:root {
--spacing: 16px;
}
HTML
.section {
margin: var(--spacing);
padding: var(--spacing);
}
3. Dynamic Button Colors
CSS
:root {
--btn-primary: #007bff;
--btn-secondary: #6c757d;
}
.btn-primary {
background: var(--btn-primary);
}
.btn-secondary {
backgroundy: var(--btn-secondary);
}
Best Practices
- Always declare global variables inside :root.
- Use descriptive names (--primary-color, not --pc).
- Provide fallback values with var().
- Use variables for repetitive values (colors, spacing, fonts).