Christian Heilmann

CSS is awesome: A dark/light mode switch with preference detection in 15 lines of CSS

Tuesday, January 26th, 2021 at 9:37 pm

I just love how far CSS has come in the last few years. With custom properties and media queries you can achieve so much in just a few lines of code.

For example, these 15 lines make sure that users of light mode in their operating systems get a black on white document and those with a dark mode setting a white on dark one:

:root {
  --foreground: #111;
  --background: #f8f8f8;
}
@media (prefers-color-scheme: dark) {
  :root {
    --foreground: #f8f8f8;
    --background: #111;
  }
}
body {
  font-family: helvetica, sans-serif;
  color: var(--foreground);
  background: var(--background);
}

We define two properties called foreground and background and set them to dark on white as a default. We then check if the preferred colour scheme is dark using a media query and flip them if it is. Instead of fixed colours for color and background we use the properties and that’s that :).

You can try it out in this codepen. Users of dark mode should get a dark document, others a light one.


See the Pen
Target styling demo
by Christian Heilmann (@codepo8)
on CodePen.


You can try this out using the simulation options in Browser Developer tools :

Simulating dark/light mode with developer tools to test the CSS

CSS tricks has a great article that covers all on media queries if you want to learn more.

Share on Mastodon (needs instance)

Share on Twitter

Newsletter

Check out the Dev Digest Newsletter I write every week for WeAreDevelopers. Latest issues:

160: Graphs and RAGs explained and VS Code extension hacks Graphs and RAG explained, how AI is reshaping UI and work, how to efficiently use Cursor, VS Code extensions security issues.
159: AI pipelines, 10x faster TypeScript, How to interview How to use LLMs to help you write code and how much electricity does that use? Is your API secure? 10x faster TypeScript thanks to Go!
158: 🕹️ Super Mario AI 🔑 API keys in LLMs 🤙🏾 Vibe Coding Why is AI playing Super Mario? How is hallucinating the least of our worries and what are rules for developing Safety Critical Code?
157: CUDA in Python, Gemini Code Assist and back-dooring LLMs We met with a CUDA expert from NVIDIA about the future of hardware, we look at how AI fails and how to play pong on 140 browser tabs.
156: Enterprise dead, all about Bluesky and React moves on! Learn about Bluesky as a platform, how to build a React App and how to speed up SQL. And play an impossible game in the browser.

My other work: