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:

Dev Digest 146: 🥱 React fatigue 📊 Query anything with SQL 🧠 AI News

Why it may not be needed to learn React, why Deepfake masks will be a big problem and your spirit animal in body fat! 

Dev Digest 147: Free Copilot! Panel: AI and devs! RTO is bad! Pi plays!

Free Copilot! Experts discuss what AI means for devs. Don't trust containers. Mandated RTO means brain drain. And Pi plays Pokemon!

Dev Digest 148: Behind the scenes of Dev Digest & end of the year reports.

In 50 editions of Dev Digest we gave you 2081 resources. Join us in looking back and learn about all the trends this year.

Dev Digest 149: Wordpress break, VW tracking leak, ChatGPT vs Google.

Slowly starting 2025 we look at ChatGPT vs Google, Copilot vs. Cursor and the state of AI crawlers to replace web search…

Dev Digest 150: Shifting manually to AI.

Manual coding is becoming less of a skill. How can we ensure the quality of generated code? Also, unpacking an APK can get you an AI model.

My other work: