How to apply dark mode using Tailwind CSS

One of the most highly desired features on the internet today is dark mode functionality. Websites and mobile applications have since begun jumping on this train. In this Answer, we’ll learn how to apply dark mode using Tailwind CSS, the most widely used CSS framework.

Set up Tailwind CSS

Firstly, we must install Tailwind CSS in our project before we can proceed. Tailwind has provided detailed documentation.

Two techniques to implement dark mode

  1. media: This method relies on the default color scheme of our operating system. We set our darkMode option to media in the tailwind.config.js file to implement this.

  1. class: Manual switching between light and dark modes is made possible with the class strategy, which is considered the most effective. To enable this, we set darkMode to class in the tailwind.config.js file like we did above. We have to include a class dark to our html tag like so:

<html lang="en" class="dark">

Next, for our dark mode to come alive, we need to add the dark prefix to a class in our element:

<body class="dark:bg-gray-600 dark:text-gray-100"></body>

The result of the code above will be a white text against a dark background. Ensure that the chosen colors match in appearance by taking into account their compatibility.

You can take a look at the code below:

@tailwind base;
@tailwind components;
@tailwind utilities;

.display-none {
    @apply hidden;
}
Coding example

Summary

  • Use a class strategy because it supports toggling manually.

  • Add a dark: prefix to your classes to enable the dark mode appearance.

Free Resources