prefers-color-scheme and Dark Mode Support
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
Detecting the User's System Theme
@media (prefers-color-scheme: dark) {
body {
background: #111827;
color: #f3f4f6;
}
}prefers-color-scheme reads the theme the user has already chosen at the operating system level, letting a site automatically match it without requiring the visitor to find and click a theme toggle first.
The Cleaner Approach: Custom Properties
:root {
--bg: #ffffff;
--text: #111827;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #111827;
--text: #f3f4f6;
}
}
body {
background: var(--bg);
color: var(--text);
}Rather than repeating a dark-mode override for every single selector, redefining a small set of custom properties inside the media query lets every rule that already uses var(--bg) and var(--text) update automatically.
Supporting a Manual Toggle Too
:root[data-theme="dark"] {
--bg: #111827;
--text: #f3f4f6;
}Many sites combine both: prefers-color-scheme sets the default based on system settings, while a manual toggle (implemented with a small amount of JavaScript setting a data-theme attribute) lets a visitor override that default and have their choice remembered.
Things Easy to Overlook in Dark Mode
- Images and icons designed for a light background can look harsh or lose contrast on a dark one.
- Shadows that work well on white backgrounds often need to be lighter or removed entirely in dark mode.
- Color contrast should be re-checked in dark mode specifically - a pairing that passes on white does not automatically pass on a dark background.