CSSDark-ModeVariablesUX
Implement Dark Mode in 5 Minutes with CSS Variables
3.31 min read
Md Nasim Sheikh
Dark mode isn't a "feature" anymore; it's an accessibility requirement. And thanks to CSS Variables, it's trivial to implement.
Advertisement
Step 1: Define Variables
Don't set colors directly (color: black). Set semantic variables.
:root {
/* Default (Light Mode) */
--bg-primary: #ffffff;
--text-primary: #1a1a1a;
--accent: #2563eb;
--card-bg: #f3f4f6;
}
Step 2: Media Query Magic
Use @media (prefers-color-scheme: dark) to override those variables.
@media (prefers-color-scheme: dark) {
:root {
--bg-primary: #111827;
--text-primary: #f9fafb;
--accent: #60a5fa;
--card-bg: #1f2937;
}
}
Step 3: Use the Variables
Now, write your CSS once.
body {
background-color: var(--bg-primary);
color: var(--text-primary);
transition: background-color 0.3s ease, color 0.3s ease;
}
.card {
background: var(--card-bg);
border: 1px solid var(--accent);
}
Adding a Toggle Button (The User Override)
System preference is great, but users like control. To support a manual toggle, use a data attribute on the <html> tag.
/* Force Dark Mode when attribute is present */
[data-theme="dark"] {
--bg-primary: #111827;
--text-primary: #f9fafb;
/* ... re-declare dark variables */
}
Then toggle it with JS:
document.documentElement.setAttribute('data-theme', 'dark');
Advertisement
Test Your Understanding
Quick Quiz
Which CSS media query detects if the user has requested the system use a light or dark color theme?
Conclusion
CSS Variables (--var) are reactive. When the media query changes (e.g., sunset triggers system dark mode), your entire site updates instantly without a page reload.
Written by
Md Nasim Sheikh
Software Developer at softexForge
Verified Author150+ Projects
Published: