CSS for Markdown, dark mode

This is the ninth part of some posts on using CSS in and with DT/DTTG. Though I wrote it as a single piece, I broke it up in smaller installments to keep the posts (barely) managable. Please let me know (preferably by a PM) if you find errors of any kind or are missing details. I’ll correct the first ones and try to help with the second ones.

Previous post

What about dark mode?

Until now, all examples were assuming that the document is displayed as dark text on a white background. That would look weird on a device set to dark mode, where text should be light on a dark background. But fortunately, CSS is able to determine if the device is currently set to dark mode.

This is achieved with a “media selector” like so:

@media (prefers-color-scheme: dark) {
  ... style definitions go here;
}

The simplest style definition for dark mode would be something like

body {
  background-color: black;
  color: white;
}

and you have to make sure to put this inside the curly braces following the media selector like so:

@media (prefers-color-scheme:dark) {
  body {
    background-color: black;
    color: white;
  }
}

This is just the most basic setting. If you use a more complex color scheme, you need to verify that it is rendered nicely in dark mode. For example, all but the lightest shades of gray might be difficult to recognize.

If you’re using borders, you might want to make them wider in dark mode since light on dark is more difficult to see than dark on white. Also, a font with very fine character stems might not be a good idea for dark mode, since these stems are harder to recognize.

Whatever special styling you want to apply, make sure it goes inside the media selector’s curly braces.

Of course, if you prefer dark over light mode anyway, you could set up the main part of your CSS so that it works well on a dark background. And then use

@media (prefers-color-scheme:light) {
    body {
    background-color: white;
    color: black;
  }
}

as a starting point for a light mode style sheet.

2 Likes