DEV Community

Cover image for Simple Dark/Light mode

Simple Dark/Light mode

matoval on May 13, 2020

Here is the simplest way I found to add dark mode to a project: Add a toggle button in your HTML with a checkbox and an onClick calling a JavaScrip...
Collapse
 
drawcard profile image
Drawcard

In addition you can implement prefers-color-scheme media queries to also trigger dark mode, if this is set in user preferences: developer.mozilla.org/en-US/docs/W...

@media (prefers-color-scheme: dark) {
  --bg: black;
  --font-color: white;
  --btn-bg: white;
  --btn-color: black;
}
Collapse
 
khuongduybui profile image
Duy K. Bui

I also read somewhere that you can also hook into the ambient sensor of the laptop.

Not sure if the following was the original published source but that's where I read it.
blog.arnellebalane.com/using-the-a...

Collapse
 
matoval profile image
matoval

That's awesome!

Collapse
 
matoval profile image
matoval

Do you have a link to your code? The code I posted in the article are only the parts of the code that have to do with dark/light mode.

Collapse
 
michaeltharrington profile image
Michael Tharrington

Love the way this dark/light mode functions.

Also, seriously cool cover image for this post. 😀

Collapse
 
matoval profile image
matoval

Thanks 😁!

Collapse
 
ben profile image
Ben Halpern

This is slick. Similar to how DEV does it but this is more elegant.

Collapse
 
matoval profile image
matoval

Thank you for the kind words!

Collapse
 
bayuangora profile image
Bayu Angora • Edited

I use dark mode too. But your method is more simple and straightforward.

 
matoval profile image
matoval

I added the codepen at the bottom of the article.

Collapse
 
alexi_be3 profile image
Alexi Taylor 🐶

But what about IE? Aren't CSS variables not supported in that unsightly browser?

Collapse
 
mrxinu profile image
Steve Klassen (They/Them)

That's pretty slick.

 
matoval profile image
matoval

OnClick the C needs to be capitalized

Collapse
 
nathankurz91 profile image
Nathan Kurz

This is pretty awesome. So cool seeing such an easy way to implement such a highly requested feature in many applications.

 
matoval profile image
matoval

You have two head tags

Thread Thread
 
matoval profile image
matoval

I'll write this code in a codesandbox and add it to the article.