48

Dark mode on the web with `prefers-color-scheme`

 4 years ago
source link: https://www.tuicool.com/articles/aI3qIrn
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

This site has a dark mode and a light one. Which mode you see depends on the setting of your device. Try it!

byUBru3.gif

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.

If you'd like to hear about other projects of mine, subscribe to my newsletter !


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK