- Instant help with your CSS coding problems

Implement Dark mode with TailwindCSS

The dark mode is everywhere these days. Websites, applications, and operating systems, you'll find the dark/light mode toggle almost everywhere.
In this article, I will give a short presentation on how you can implement dark mode on your own website using TailwindCSS.

Dark or light mode

The first task is to decide whether to use a dark or light color scheme. There are two options here. One is to manage the current value of the dark/light mode yourself and the other is to use the value set at the operating system level. For the perfect solution, you need to combine the two. The OS-level system setting can be read out using the JavaScript window.matchMedia method as follows:

let darkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;

 

Activate dark mode in Tailwind config

There are several ways to implement dark mode using TailwindCSS, but the currently recommended solution is to use the dark class. To do this, you must first extend the tailwind configuration file. In the tailwind.config.js file, insert the darkMode: 'class' line in the exports block like this:

module.exports = {
  content: ['**/*.html'],
  darkMode: 'class',
  theme: {
    extend: { },
  },
  plugins: [],
}

 

Mark the HTML to use dark mode

If you want to switch to dark mode, add the dark helper class to the parent container of the block you want to repaint. Since we usually want to change the look of the whole page and not just a paragraph, the most optimal place for the dark class is the html element.

<!DOCTYPE html>
<html lang="en" class="dark">
    <head>
    </head>
    <body>
    </body>
</html>

Prepare elements for dark mode

Once the dark class is in place, we can customize the individual elements. For each element where color is used, the default value defines the normal color that will be displayed in light mode. To define the color for dark mode, you need to use the dark: prefix, so:

<body class="p-10 bg-white dark:bg-black">
    <h1 class="text-3xl py-3 text-amber-300 dark:text-amber-800">Dark Mode!</h1>
    <div class="p-2 border bg-slate-50 dark:bg-slate-950 border-slate-300 dark:border-slate-700 text-slate-500 dark:text-slate-600">
        Lorem ipsum dolor sit amet.
    </div>
</body>

Reference

TailwindCSS Dark mode reference

MDN Color schemes reference

MDN matchMedia reference

 

Share "Implement Dark mode with TailwindCSS" with your friends