Dark mode in a website with CSS
September 27, 2019This site has a dark mode and a light one. Which mode you see depends on the setting of your device. Try it!
The instant change in appearance is accomplished by this appendix to the style sheet:
@media (prefers-color-scheme: dark) {
body {
background-color: #444;
color: #e4e4e4;
}
a {
color: #e39777;
}
img {
filter: grayscale(30%);
}
}
This works in Firefox, Safari, and Chrome among other browsers.
Light on dark
The most important block is the one that overrides the colors of text and the background:
body {
background-color: #444;
color: #e4e4e4;
}
It's recommended to avoid pure white for text, and I chose likewise to avoid pure black for the background.
Desaturate colors
The accent color I use for hyperlinks looked harsh on the dark background, so I overrode it with a less saturated one:
a {
color: #e39777;
}
Photographs also looked harsh. It turns out that many people prefer images, too, to be desaturated in dark mode:
img {
filter: grayscale(30%);
}
You may want to use a more specific selector here in order to treat vector images differently.
Read more
All the above is distilled from Hello darkness, my old friend by Thomas Steiner, which also contains a fascinating history of display color schemes:
With the advent of more sophisticated WYSIWYG desktop publishing, the idea of making the virtual document resemble a physical sheet of paper became popular…
The first ever browser, WorldWideWeb, displayed webpages this way. Fun fact: the second ever browser, Line Mode Browser—a terminal-based browser—was green on dark.
Update: This post is discussed on Hacker News and Reddit.
If you'd like to hear about other projects of mine, subscribe to my newsletter!