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
media: This method relies on the default color scheme of our operating system. We set ourdarkModeoption tomediain thetailwind.config.jsfile to implement this.
class: Manual switching between light and dark modes is made possible with theclassstrategy, which is considered the most effective. To enable this, we setdarkModetoclassin thetailwind.config.jsfile like we did above. We have to include a classdarkto ourhtmltag 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>
@tailwind base;
@tailwind components;
@tailwind utilities;
.display-none {
@apply hidden;
}Summary
Use a
classstrategy because it supports toggling manually.Add a
dark:prefix to your classes to enable the dark mode appearance.