Use dark mode with TailwindCSS

January 15, 2021
views 2 min read

For this tutorial I'm assuming we already have an application using TailwindCSS. If you need some references you can always take a look at this post, where I go through how to setup NextJS + TailwindCSS.

Activate dark mode

So, first of all we'll need to change a little bit the configuration on our tailwind.config.js file and set darkMode to class:

module.exports = {
  purge: ['./pages/**/*.js', './components/**/*.js'],
  darkMode: 'class', // or 'media' or 'class'
  theme: {
    extend: {},
  variants: {
    extend: {},
  plugins: [],

Alright, for this to take effect we'll need to restart our application.

The Class

For the sake of keeping this tutorial simple we'll not go through switching a dark class in our <html> tag.

So, to test this out, change your <html> tag and add the dark class:

<html class="dark"></html>

Once you're done it's really a matter of playing with TailwindCSS's own dark: utility. It's pretty neat, check this example:

<h1 class="text-white">Hey there!</h1>

So, we're setting our title color to black, pretty straight forward. To set a new color when it's in dark more just add another utility class:

<h1 class="text-black dark:text-white">Hey there!</h1>

You can use dark: pretty much with every other utility class:


And so on. That's it ✌🏻

Read next
How to use custom hooks with React
March 16, 2021