Dark Mode
Dark themes, color schemes, prefers-color-scheme, and theme switching.
Overview
Dark mode reduces eye strain and saves battery on OLED screens.
Key Concepts
- prefers-color-scheme — System preference
- Data attributes — Theme toggling
- Color variables — Theme tokens
- Contrast — Readable text
- Transitions — Smooth theme switching
Code Examples
/* System preference */
:root {
--bg: #ffffff;
--text: #1a1a1a;
--primary: #007bff;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #1a1a1a;
--text: #ffffff;
}
}
/* Data attribute theme */
[data-theme="dark"] {
--bg: #1a1a1a;
--text: #ffffff;
--card-bg: #2a2a2a;
--border: #444;
}
[data-theme="light"] {
--bg: #ffffff;
--text: #1a1a1a;
--card-bg: #ffffff;
--border: #ddd;
}
body {
background: var(--bg);
color: var(--text);
transition: background 0.3s, color 0.3s;
}
/* Theme toggle button */
.theme-toggle {
position: fixed;
top: 1rem;
right: 1rem;
padding: 0.5rem 1rem;
border: none;
border-radius: 9999px;
cursor: pointer;
background: var(--card-bg);
color: var(--text);
border: 1px solid var(--border);
}
/* Dark mode images */
@media (prefers-color-scheme: dark) {
.logo {
filter: invert(1);
}
.photo {
filter: brightness(0.8);
}
}
/* Theme-aware components */
.card {
background: var(--card-bg);
border: 1px solid var(--border);
border-radius: 8px;
padding: 1.5rem;
}
/* Smooth transitions */
* {
transition: background-color 0.3s, color 0.3s, border-color 0.3s;
}
/* High contrast mode */
@media (prefers-contrast: high) {
:root {
--text: #000000;
--bg: #ffffff;
}
}
/* Reduced motion */
@media (prefers-reduced-motion: reduce) {
* {
transition: none !important;
}
}
// Theme switching JavaScript
const themeToggle = document.getElementById('theme-toggle');
const html = document.documentElement;
// Check for saved preference
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
html.setAttribute('data-theme', savedTheme);
}
// Toggle theme
themeToggle.addEventListener('click', () => {
const current = html.getAttribute('data-theme');
const next = current === 'dark' ? 'light' : 'dark';
html.setAttribute('data-theme', next);
localStorage.setItem('theme', next);
});
Practice
Implement dark mode with system preference detection and manual toggle.