Dark mode uses dark backgrounds with light text—great for low light environments or saving battery. It's like switching from a bright room to a cozy lamp—easier on the eyes at night.
This demo uses CSS custom properties (variables) that change when a
data-theme="dark"
attribute is applied to the HTML element. The colors smoothly transition thanks to CSS transitions.
/* Define color variables for both themes */
:root {
--bg-primary: #ffffff;
--text-primary: #212529;
--accent: #667eea;
}
[data-theme="dark"] {
--bg-primary: #1a1a1a;
--text-primary: #e9ecef;
--accent: #8b9eff;
}
/* Use variables in your styles */
body {
background: var(--bg-primary);
color: var(--text-primary);
transition: all 0.3s ease;
}
Easier on eyes in low-light conditions, especially at night or in dark rooms.
OLED screens use less power when displaying dark colors, extending battery life.
Many users prefer dark interfaces. Offering a choice shows you respect preferences.
Dark mode is trendy and can make designs feel more premium and sophisticated.
Modern browsers can detect the user's system preference using the
prefers-color-scheme
media query:
/* Automatically apply dark mode based on system preference */
@media (prefers-color-scheme: dark) {
:root {
--bg-primary: #1a1a1a;
--text-primary: #e9ecef;
}
}
/* JavaScript to detect preference */
const prefersDark = window.matchMedia(
'(prefers-color-scheme: dark)'
).matches;
if (prefersDark) {
document.documentElement.setAttribute(
'data-theme', 'dark'
);
}
Dark mode isn't just inverting colors! You need to carefully adjust contrast:
// Save preference to localStorage
function toggleTheme() {
const html = document.documentElement;
const current = html.getAttribute('data-theme');
const next = current === 'dark' ? 'light' : 'dark';
html.setAttribute('data-theme', next);
localStorage.setItem('theme', next);
}
// Load saved preference on page load
function loadTheme() {
const saved = localStorage.getItem('theme');
const prefersDark = window.matchMedia(
'(prefers-color-scheme: dark)'
).matches;
const theme = saved || (prefersDark ? 'dark' : 'light');
document.documentElement.setAttribute('data-theme', theme);
}
// Run on page load
loadTheme();
Explora el enfoque Checkbox + CSS (método CSS puro) en una demo separada:
Ver Demo del Camino C →