How To Add Dark Mode To A Web Page

Recently I finished adding darkmode to my side project, dotRemote.io. In this short post I want to show a simple way to detect whether the user has dark mode enabled in his system and show how to easily add dark mode to any website, plus, make it switchable.

Dark Mode CSS

To be able to render the site dark version and be able to switch between dark and light mode, a class can be added to the document body.

This way, all the dark mode CSS can be styled based on the presence of this class in the body:

body.dark-mode .my-div {
  background: #000;
}

.my-div {
  background: #FFF;
}

Detecting Dark Mode

The simplest way to detect if the user has dark mode set in his system is by using the following snipped:

if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
  // ...
}

We can add this small snippet at the end of the body of the page and use it to add the dark-mode class to the body element to render the dark version of the page:

<script>
  if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    document.body.classList.add('dark-mode')
  }
</script>

With the following code, dark/light mode can be toggled based on a button click:

document.querySelector('.toggle-dark-mode').addEventListener('click', () => {
  document.body.classList.toggle('dark-mode')
})

And that's it!