The Last CSS Dark Mode Tutorial You’ll Read

You want to enable dark mode for your website, right? Like this?

First of all, create your default theme colors for your website. Something like:

:root {
  --colorBackground: white;
  --colorForeground: black; // think of this as the font color

  --colorContainer: white;

}

Calm down! We’re not done. Don’t ask me what the :root means. I don’t remember

Then, when dark mode is enabled, what major colors do you want changed? You specify that next via the .dark class, which will be dynamically applied to the body tag when the user either toggles dark mode, or your code (which we’ll see soon) automatically enables the dark mode based on their OS preference.

.dark {
  // just flipped the colors
  --colorBackground: black;
  --colorForeground: white;


  --colorContainer: grey;
}

With the above in place, you can then apply the --colorBackground variable to your, say, body tag

body {
  ...
  background-color: var(--colorBackground);
  color: var(--colorForeground);
  ...

}

Now you need a way to trigger the toggle. Via Javascript, you can do it like this:

document.getElementById('darkbody')?.classList.toggle('dark');

The above assumes you have an id of darkbody on the body tag in your HTML

In my Angular code, it looks like this in Template and Component

<!-- Template -->
<!-- CSS Icon from here: https://css.gg/dark-mode
<div class="dark-mode-toggle">
  <i class="gg-dark-mode" (click)="darkMode()"></i>
</div>
// component
...  
darkMode() {
  document.getElementById('darkbody')?.classList.toggle('dark');
}
...

Thus, anytime the icon is clicked, the .dark class will be added or removed.

Now, if you want to automatically detect whether a user prefers dark mode on their OS i.e they’ve either enabled dark mode on their phone OS or Windows/Linux, check for the prefers-color-scheme

Do that like this:

    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
      console.log('User likes dark mode');
      this.darkMode();
    }

Done. Now go forth and never read yet another CSS dark mode article again.

Cheers

This article was inspired by this Codepen

Exit mobile version