DEV Community

Discussion on: Add dark mode to your website with just a few lines of code

Collapse
 
taufik_nurrohman profile image
Taufik Nurrohman

Another idea: use single theme file and just toggle a global class name…

button.addEventListener('click', () => {
    document.body.classList.toggle('dark');
    localStorage.setItem('theme', document.body.classList.contains('dark') ? 'dark' : 'light');
});

if (localStorage.getItem('theme') === 'dark') {
    document.body.classList.add('dark');
}
Enter fullscreen mode Exit fullscreen mode
/* Light mode */
body {
  background: #fff;
  color: #000;
}

/* Dark mode */
body.dark {
  background: #000;
  color: #fff;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
albertomontalesi profile image
AlbertoM

Yes you are right, I might add it to the article for completion.

Collapse
 
mx profile image
Maxime Moreau

And even better, define some css variables to change everything in just a few lines of css (variables declaration).

Collapse
 
anjali1102 profile image
Anjali Chauhan

i have more than 1 page whom i want to add dark theme. how to do that?

Collapse
 
iamarsenibragimov profile image
Arsen Ibragimov

Good one! Thanks!

Collapse
 
anjali1102 profile image
Anjali Chauhan

i have more than 1 page whom i want to add dark theme. how to do that?