CSS Variables (Custom Properties)
CSS Variables bring real programming power into standard stylesheets, enabling instant theming and dark mode switches.
What is it?
CSS Custom Properties (commonly known as CSS Variables) are entities defined by CSS authors that contain specific values to be reused throughout a document, prefixed with `--` and accessed via `var(--name)`.
Why is it used?
Centralizes design tokens (colors, font sizes, borders, spacing) in one place. Makes switching between Light Mode and Dark Mode seamless with a single attribute toggle.
Detailed Explanation
Syntax Structure
:root {
--primary: #1c1c1c;
--bg: #f7f4ed;
}
body {
background-color: var(--bg);
color: var(--primary);
}
Code Example
/* Global Design Tokens */
:root {
--bg-primary: #f7f4ed;
--bg-card: #fcfbf8;
--text-main: #1c1c1c;
--text-muted: #5f5f5d;
--border: #eceae4;
--radius-card: 12px;
}
/* Instant Dark Theme Override */
[data-theme="dark"] {
--bg-primary: #121212;
--bg-card: #1c1c1c;
--text-main: #fcfbf8;
--text-muted: #a1a1aa;
--border: #2e2e2e;
}
/* Components automatically adapt to current theme */
body {
background-color: var(--bg-primary);
color: var(--text-main);
transition: background-color 0.25s ease, color 0.25s ease;
}
.card {
background-color: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius-card);
padding: 20px;
}
Explanation of the Code
Expected Output
Real-World Application
Used by GitHub, Lovable, Tailwind CSS, and IGM Computers for effortless dark mode toggling.
Common Mistakes to Avoid
Quick Practice Challenge
Define a `--brand-color: #2563eb;` in `:root` and use it on a button's background.