That blinding white screen you look at under the covers at night—it’s rough, isn’t it? That’s why many people set their phone or PC to dark mode (a black-based color scheme). If you receive that setting in CSS, your page will automatically switch to a night look too.
How to write it: everyday colors + a night override
First write the everyday (light) colors, then override only for dark mode.
body {
background: #ffffff;
color: #333333;
}
@media (prefers-color-scheme: dark) {
body {
background: #1b1b1f;
color: #e6e6e6;
}
}When someone set to dark mode opens the page, the background switches to a deep color and the text to a bright one, automatically. Not a single line of JavaScript needed.
CSSMake it look good on phones too: media queriesYou can review how@media itself works in the media queries lessonLet’s see it in motion
The real thing has the browser respond automatically to the OS setting, but in this demo we switch it with a button as a stand-in.
Three things to watch for with night colors
- Don’t go pure black × pure white —
#ffftext on a#000background has too strong a contrast and tires the eyes. A slightly lighter black like#1b1b1ffor the background and a slightly darker white like#e6e6e6for the text are the standards - Check readability at night too — flip the colors and a combination that was readable in light mode can become unreadable. The passing line for contrast ratio is the same in dark mode
- You don’t need to prepare every color — the background and text color are plenty to start. Cards and borders can come little by little, once the page grows
Tell the browser’s standard parts too: color-scheme
:root {
color-scheme: light dark;
}prefers-color-scheme was a signal that works on your own CSS, but color-scheme is a signal to the browser’s own parts. Write this and standard parts you never colored yourself—like scrollbars and checkboxes—will also switch automatically to match the setting.
Summary of this lesson
- With
@media (prefers-color-scheme: dark), you can write CSS that works only for people set to dark mode - Write the everyday colors first, and override only for dark
- Avoid pure black × pure white, and use a slightly softened black and white