loading...

Create A Dark/Light Mode Switch with CSS Variables

Ananya Neogi on April 10, 2019

Giving your users a way to customise the interface to their preference is a huge win for user experience. Here we are going to provide the user wit... [Read Full]
pic
Editor guide
 

Just how we do it with dev.to!

CSS variables are awesome.

 

Wait, what! There is dark theme for dev.to, nobody told me about that. πŸ˜‚

 

Dark mode is new, and it's fabulous (with a few kinks that still need to be worked out).

Oh! I see. How can I enable dark mode?

Settings ➑ Misc. On that page you'll find it under "Style Customization"

Awesome, thanks. Looks cool.

Dark mode for dev.to

 

Love the dark mode on dev.to! πŸ™‚

 

@Ananya Neogi

Hi,

Dark mode does not not work link open new window (target="_blank" links)

is there a solution?

Thanks
Best regards

 

Where is bro? Just tell me where is it? I didn't know about it...

 

Instead of using the following instruction you used, which forces two calls to localStorage (which is pretty slow),

const currentTheme = localStorage.getItem('theme') ? localStorage.getItem('theme') : null;

you could use an or operator.

// Value at right-hand side of || is the default
const currentTheme = localStorage.getItem('theme') || null;

or, in this case, as the default is null, even simpler,

const currentTheme = localStorage.getItem('theme');

by taking the property of localStorage.getItem to return null on unknown key to directly return the expected value/default.

 

Yes, this makes more sense. Thanks! πŸ™‚
I'll update the demo.

 

Hey just found a simple error in your CSS

.theme-switch-wrapper {
display: flex;
align-items: center;

em {
margin-left: 10px;
font-size: 1rem;
}
}

You have a nested selector here, this does not work in CSS only SCSS

so to fix it I just broke out the one selector to be on its own and not nested one!

.theme-switch-wrapper {
display: flex;
align-items: center;
}

.theme-switch-wrapper em {
margin-left: 10px;
font-size: 1rem;
}

 

CSS variables are fantastic for use cases like this. Here's a <dark-mode-toggle> that initially respects prefers-color-scheme and allows for manual overrides. Read more about it in this article.

 
 

Thanks for this! I haven't tried my own light/dark mode since I tried implementing it on my first bootcamp project a couple years ago. I technically got it to work, but the code was not this DRY as I made two individual buttons that would add/remove a "dark" or "light" class on the entire body element. πŸ˜‚ Your solution is much better!

 

Just added mine over at felixparadis.com :)

Quick note about accessibility though:
If you just display:none; your input, you're making it unaccessible through keyboard navigation.
Just hide it behind the label instead and everyone can toggle πŸŽ‰
Then add aria-label="Switch visual theme" to your input and blind users can know what's it about.

 

I'm planning to experiment with something like this, but using CSS only (no javascript).

 

I keep trying to serve it via ng serve but instead i get the error "Property 'checked' does not exist on type 'Element" referring to "if (currentTheme) {
document.documentElement.setAttribute('data-theme', currentTheme);

if (currentTheme === 'dark') {
    toggleSwitch.checked = true;
}

}"

 

You won't believe it, but actually you can nowadays even take the operation system setting for the dark mode and apply/get that, so your users don't even need that toggle, or at least use the version they prefer, by default.
With CSS and JS…

 

In my case, I would offer two toggle for users which are auto mode (system dark mode) and manual Light/Dark toggle, so users can choose whatever they prefer.

 

this doesn't work for me. console says 'toggleSwitch is null'

 

add the code after the switch in tags

 

Add the JS inside DOMContentLoaded method

 

Thanks for this great post Ananya. I followed the instructions and managed to get the page up and running. But i am getting a console log Error: script5007 unable to get property 'addEventListener' for undefined or null source. Could someone please help me with a solution. Thanks.

 

Very cool.

Have you thought about the prefers-color-scheme media feature? How could this be implemented in this script? You should check that too In my opinion. The toggle would have to automatically switch to the preferred color scheme.

 

Thanks! It will help me a lot. I've been using it wrong (but working), now you've cleared my mind. :)

 

How we can set this for all pages?

 

this is great and so helpful - thanks so much! I do have one question - in the js, where does "light" come from? unless I'm missing it, that's not defined in the CSS, is it?

 

Hi Desi!
You're right, it's not defined anywhere.
If CSS doesn't find any specific styles related to light it will default back to the normal variables defined in :root.

Why I added it?
I added it so that we can use it while checking for the saved theme in localStorage further and add it to the root element. It will also be useful in cases where you might want to add some specific styles for light apart from the default styles.

I hope this helps πŸ™‚

 

Awesome, thanks so much! Explanation makes perfect sense.

You're welcome πŸ™‚

 

Great post. I would love to add a Dark theme to my website, but probably won’t have the time 😭. Bookmarked your article anyways πŸ€“

 

Super duper thanks for article.

 

Thank you Ananya! Great article, loved the tip about how to come up with a night theme :)

 

Thank you for taking the time to write this article, it has been a great help! Would you follow this for all types of run time theming too, or do you think there is a better way to have multiple themes which people can switch between?

 

Thanks Ananya, it's helpful for me

 

Nice, simple and works well even while using .less .

 

I was exactly looking for something like this. Thanks

 

This isn't not working anymore?

 

Nice post, Thanks for writing 😁

 

Is there any way to not have the background flash the "light" color before switching to "dark"? Little jarring to the user experience.

 
 

Such a simple solution! Who needs a plugin when you can just use CSS variables!

 

A big thank! I was violently disabling dark-theme-CSS-sheet via JS for my blog, and it was creepy. This solution is way, way, way... way better!

I'm happy now.

 

How about images like the Logo in Header & Footer? How would you suggest making this happen?

 

add an image source changer in the functions or make the images a background image if you wanna change them with CSS

 

Amazing πŸ™Œ Thank you! πŸ™

 

Really enjoyed this tutorial. I just had to include it in a codepen of my own. You can view it here - codepen.io/HikwaMehluli/full/jOPPEVx

 

Thank you so much!

 

I visited your website and just loved it.
Could you help me with websites like this please.
Which language have you used for Backend? Could you make a tutorial for a simple blog website please.

 

Hi,

Dark mode does not not work link open new window (target="_blank" links)

is there a solution?

Thanks
Best regards

 

Great, thanks a lot!

I added an innerHTML to change the text as well:

 

Very Cool! Trying to figure out how to toggle between bg color & bg picture.

Code of Conduct Report abuse