This article will illustrate the method of toggling dark mode manually in Tailwind CSS.
How to Toggle Dark Mode Manually in Tailwind?
To toggle dark mode manually in Tailwind, first, open the “tailwind.config.js” file. Then, configure the dark mode in it using the “class” strategy. After that, make an HTML file and utilize the “dark” class variant with the desired classes in the HTML program. Next, view the HTML web page and change the theme of the web browser for verification.
Try out the given-provided steps for a practical demonstration:
Step 1: Configure Dark Mode in the “tailwind.config.js” File
Open the “tailwind.config.js” file and configure the dark mode using the “class” strategy:
content: ["./index.html"],
darkMode: 'class',
};
Step 2: Use the “dark” Class in HTML Program
Then, add the “dark” class in the parent element of the HTML program and use the desired styling in the main <div>. For instance, we have used the “dark” class in the <body> element and the “dark:bg-black” and “dark:text-white” classes in the main <div> element:
Here, in the <body> element, the class attribute “dark” is utilized for applying dark mode styles.
In the <div> element:
- “h-screen” class sets the height of <div> to match the screen’s height.
- “text-center” class centers the text horizontally within the <div> element.
- “bg-white” class applies white color to the background of <div> element.
- “text-black” class sets the <div> element’s text color to black.
- “dark:bg-black” class changes the background color of the <div> element to black in dark mode.
- “dark:text-white” class sets the text color of the <div> element to white in dark mode.
Step 3: Verify Output
To ensure that the dark mode has been set and working properly, view the HTML web page and change the theme of the browser:
It can be observed that the color of the web page is the same i.e., dark on both light and dark themes of the browser. It indicates that the dark mode has been manually set successfully.
Conclusion
To toggle dark mode manually in Tailwind, configure the dark mode in the “tailwind.config.js” file using the “class” strategy. Then, use the “dark” class variant with the desired classes in the HTML program to set the styling for the dark mode. To ensure changes, view the HTML web page and change the theme of the web browser. This article has illustrated the method of toggling dark mode manually in Tailwind CSS.