“This is the fifth day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

Tailwind CSS is one of the fastest growing CSS frameworks today. Even though Tailwind has a very good dark mode integration guide, there is no clear explanation of how to build a switch element to toggle it. Most importantly, Tailwind does not include any actual components that support dark mode.

This is where Flowbite comes in. Flowbite is a library that provides components and interactive elements on top of Tailwind CSS. As of version 1.2, it supports dark mode.

That’s what I’m going to show you today — how to build Tailwind CSS dark mode switch elements and how to use the Flowbite component.

Tailwind CSS official website.

Before diving into this tutorial, make sure you have the Tailwind CSS project set up. You should alsoInstall Flowbite as a plug-inSo that you can use its components in dark mode.

How to install Tailwind CSS

The most popular way to use Tailwind CSS is to install it as a PostCSS plug-in. To do this, we need to install three different packages using NPM:

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
Copy the code

After that, you should create a file called postcss.config.js and add the following code to it:

// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}
Copy the code

Now open your terminal and execute the following command:

npx tailwindcss init
Copy the code

This will create an empty tailwind.config.js file that we will use later to include Flowbite as a plug-in.

Next, you should create a new CSS file. You can call it styles.css and add the following code to it:

/* ./your-css-folder/styles.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
Copy the code

After compiling the code with PostCSS, the injected instructions (base, component, utility) are used as styles in the final CSS file.

Finally, all you need to do is use Tailwind CLI to compile CSS by running the following command:

npx tailwindcss -o tailwind.css
Copy the code

A newly created tailwind. CSS file will be available in your project and you should include it in the HTML template to access the styles.

You now have a Tailwind CSS configuration available locally on your computer. If you want to learn more about this process, check out the Tailwind CSS installation guide.

How do I install Flowbit

We need to install Flowbite to access the full functionality and dark version support of the component. Fortunately, the setup process is very simple, as it is a Tailwind CSS plug-in.

Let’s first install it via NPM:

npm i @themesberg/flowbite
Copy the code

Then file it as a plug-in request tailwind.config.js:

module.exports = {

    plugins: [
        require('@themesberg/flowbite/plugin')
    ]

}
Copy the code

Finally, make sure to include JavaScript files somewhere before the tag closes:

<script src=".. /path/to/@themesberg/flowbite/dist/flowbite.bundle.js"></script>Copy the code

How to enable dark mode in Tailwind CSS

The first thing to understand is how dark mode works in Tailwind CSS. You can set this up in two ways:

  • usemediaoptions
  • useclassoptions

The main difference is that the media option only takes into account the browser’s color scheme preferences, which are actually set by the operating system.

This class option will only find. Dark applied to classes with the main < HTML > tag. This is what most websites use because with this method, users can manually set their preferences.

We’ll stick with this class option because it gives users more control over their theme preferences.

Let’s first add the following to the tailwind.config.js file:

module.exports = {
  darkMode: 'class',
  // ...
}
Copy the code

Tailwind CSS in dark mode

This will configure Tailwind to use the class dark mode option.

Next, add the script to the page element. This checks previous user preferences for localStorage and uses the browser’s color scheme as a backup:

<script> // It's best to inline this in `head` to avoid FOUC (flash of unstyled content) when changing pages or themes if ( localStorage.getItem('color-theme') === 'dark' || (! ('color-theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches) ) { document.documentElement.classList.add('dark'); } else { document.documentElement.classList.remove('dark'); } </script>Copy the code

Dark mode inspector localStorage

The reason we added this script to the tag rather than before ending the tag was because we wanted to avoid the flicker effect when we set the page to dark or light mode.

How to build a dark mode switch

Now that Tailwind is configured, we need to build elements that the user will interact with to change the theme from dark mode to light mode.

To do this, we’ll stick to a basic element from the Flowbite component library

Add the following HTML code to your page. I recommend adding this element somewhere in the upper right corner of the navigation bar, because this is the natural place for users to change their color scheme:

<button id="theme-toggle" type="button" class="text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 Focus :outline- None focus:ring-4 focus:ring-gray-200 Dark :focus:ring-gray-700 rounded- LG text-sm p-2.5" > < SVG id="theme-toggle-dark-icon" class="w-5 h-5 hidden" fill="currentColor" viewBox="0 0 20 20" XMLNS = "http://www.w3.org/2000/svg" > < path d = "M17.293 A8 13.293 8 0 a8.001 016.707 2.707 8.001 1010.586 10.586 0 z" ></path> </svg> <svg id="theme-toggle-light-icon" class="w-5 h-5 hidden" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" > <path d="M10 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm4 8a4 4 0 11-8 0 4 4 0 018 0zm-.464 1.915 l.707 -.707a1 10 00-1.414 1.414zm2.12-10.607a1 10 010 1.414l-.707-.707a1 10 00-1.414 1.414zm2.12-10.607a1 10 0 707-.707a1 10 011.414 0zM17 11a1 10 100-2h-1a1 10 100 2H1zm-7 4a1 10 011 1v1a1 10 11-2 0v-1a1 10 011-1zm5.05 6.464A1 10 106.465 5.05l-.708-.707a1 10 00-1.414 1.414l.707.707zm1.414 8.486l-.707.707 A1 10 01-1.414-1.414 L.707 -.707a1 10 011.414 1.414zM4 11a1 10 100-2H3a1 10 000 2h1z" form-rule ="evenodd" clip-rule="evenodd"  ></path> </svg> </button>Copy the code

These two SVG objects are ICONS, and only one of them is displayed according to the active theme. These three objects have three ids:

  • #theme-toggleUsed for main dark mode switching element
  • #theme-toggle-dark-iconThe moon icon that will be displayed when the active theme lights up
  • #theme-toggle-light-iconThe sun icon that will be displayed when the active theme goes dark

How do I use JavaScript to handle dark mode switching

The last thing we need to do is handle the click event for the dark mode switch element and update the and icon inside the localStorage element.

Add the following code to your main JavaScript file:

var themeToggleDarkIcon = document.getElementById('theme-toggle-dark-icon'); var themeToggleLightIcon = document.getElementById('theme-toggle-light-icon'); // Change the icons inside the button based on previous settings if (localStorage.getItem('color-theme') === 'dark' || (! ('color-theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) { themeToggleLightIcon.classList.remove('hidden'); } else { themeToggleDarkIcon.classList.remove('hidden'); } var themeToggleBtn = document.getElementById('theme-toggle'); themeToggleBtn.addEventListener('click', function() { // toggle icons inside button themeToggleDarkIcon.classList.toggle('hidden'); themeToggleLightIcon.classList.toggle('hidden'); // if set via local storage previously if (localStorage.getItem('color-theme')) { if (localStorage.getItem('color-theme') === 'light') { document.documentElement.classList.add('dark'); localStorage.setItem('color-theme', 'dark'); } else { document.documentElement.classList.remove('dark'); localStorage.setItem('color-theme', 'light'); } // if NOT set via local storage previously } else { if (document.documentElement.classList.contains('dark')) { document.documentElement.classList.remove('dark'); localStorage.setItem('color-theme', 'light'); } else { document.documentElement.classList.add('dark'); localStorage.setItem('color-theme', 'dark'); }}});Copy the code

The first part of the code changes the icon being displayed based on previous preferences, through the localStorage browser or color scheme.

The second part of the code handles the click event of the Switch element itself, and localStorage is set based on the selected theme.

How to use the dark mode switch in the navigation bar

We’re not done yet because we need to find a place to put the dark mode switcher – there’s a better place to do this than the navigation bar.

Fortunately, Flowbite comes with a number of great navigation bar components from which we can select and place the dark mode toggle button.

Let’s take the navigation bar with buttons as an example and change it using our own dark mode switcher:

<div class="bg-white border-gray-200 Pg-bg-white border-gray-200 Px-2 sm: Px-4 py-2.5 Rounded dark:bg-gray-800" class="container mx-auto flex flex-wrap items-center justify-between"> <a href="#" class="flex"> <svg class="h-10 mr-3" ViewBox = "0 0 52 72" the fill = "none" XMLNS = "http://www.w3.org/2000/svg" > < path d = "M1.87695 53 h28. 7791 c41. 53 51.877 5357 "Fill ="#76A9FA"></path><path d="M0.000409561" 32.1646L0.000409561 66.4111C12.8618 66.4111 23.2881 55.9849 23.2881 43.1235L23.2881 8.87689C10.9966 8.98066 1.39567 19.5573 0.000409561 32.1646Z" fill="#A4CAFE"></path><path d="M50.877 5h23.9748c11.2182 5 0.876953 15.2975 0.876953 28h27.7791C40.5357 28 50.877 17.7025 50.877 5Z" fill="#1C64F2"></path></ SVG >< span class="self-center text-lg font-semibold whitespace-nowrap dark:text-white">FlowBite</span> </a> <div class="flex md:order-2"> <! -- Dark mode switcher --> <button id="theme-toggle" type="button" class="text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 focus:outline-none focus:ring-4 focus:ring-gray-200 dark:focus:ring-gray-700 Rounded - LG text-sm P-2.5 "> < SVG id="theme-toggle-dark-icon" class=" W-5 H-5 hidden" fill="currentColor" viewBox="0 0 20" 20 "XMLNS =" http://www.w3.org/2000/svg "> < path d =" M17.293 A8 8 0 a8.001 016.707 2.707 8.001 13.293 1010.586 10.586 0 z" ></path> </svg> <svg id="theme-toggle-light-icon" class="w-5 h-5 hidden" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" > <path d="M10 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm4 8a4 4 0 11-8 0 4 4 0 018 0zm-.464 1.915 l.707 -.707a1 10 00-1.414 1.414zm2.12-10.607a1 10 010 1.414l-.707-.707a1 10 00-1.414 1.414zm2.12-10.607a1 10 0 707-.707a1 10 011.414 0zM17 11a1 10 100-2h-1a1 10 100 2H1zm-7 4a1 10 011 1v1a1 10 11-2 0v-1a1 10 011-1zm5.05 6.464A1 10 106.465 5.05l-.708-.707a1 10 00-1.414 1.414l.707.707zm1.414 8.486l-.707.707 A1 10 01-1.414-1.414 L.707 -.707a1 10 011.414 1.414zM4 11a1 10 100-2H3a1 10 000 2h1z" form-rule ="evenodd" clip-rule="evenodd"  ></path> </svg> </button> <! -- Dark mode switcher end --> <button data-collapse-toggle="mobile-menu-4" type="button" class="md:hidden text-gray-500 hover:bg-gray-100focus:outline-none focus:ring-2 focus:ring-gray-200 rounded-lg text-sm p-2 inline-flex items-center dark:text-gray-400 dark:hover:bg-gray-700 dark:focus:ring-gray-600" aria-controls="mobile-menu-4" aria-expanded="false">  <span class="sr-only">Open main menu</span> <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1  0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 15a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clip-rule="evenodd"></path></svg> <svg class="hidden w-6 h-6" fill="currentColor" viewBox="0 0 20 20" XMLNS = "http://www.w3.org/2000/svg" > < path the fill - rule = "evenodd" d = "M4.293 4.293 a1 1 0 0 l10 l4.293 8.586-011.414 4.293 a1 1 0 111.414 1.414 L11.414 10 l4. 293 a1 1 0 01-1.414 4.293 1.414 L10 11.414 l - 4.293 4.293 a1 1 0 01 L8.586 10 1.414-1.414-4.293 5.707 A1 10 010-1.414z" clip-rule="evenodd"></path></ SVG ></ button> </div> <div class="hidden MD :flex justify-between items-center w-full md:w-auto md:order-1" id="mobile-menu-4"> <ul class="flex-col md:flex-row flex md:space-x-8 mt-4 md:mt-0 md:text-sm md:font-medium"> <li> <a href="#" class="bg-blue-700 md:bg-transparent text-white block pl-3 pr-4 py-2 md:text-blue-700 md:p-0 rounded dark:text-white" aria-current="page">Home</a> </li> <li> <a href="#" class="text-gray-700 hover:bg-gray-50 border-b border-gray-100 md:hover:bg-transparent md:border-0 block pl-3 pr-4 py-2 md:hover:text-blue-700 md:p-0 md:dark:hover:text-white dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent dark:border-gray-700">About</a> </li> <li> <a href="#" class="text-gray-700 hover:bg-gray-50 border-b border-gray-100 md:hover:bg-transparent md:border-0 block pl-3 pr-4 py-2 md:hover:text-blue-700 md:p-0 md:dark:hover:text-white dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent dark:border-gray-700">Services</a> </li> <li> <a href="#" class="text-gray-700 hover:bg-gray-50 border-b border-gray-100 md:hover:bg-transparent md:border-0 block pl-3 pr-4 py-2 md:hover:text-blue-700 md:p-0 md:dark:hover:text-white dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent dark:border-gray-700">Contact</a> </li> </ul> </div> </div> </nav>Copy the code

The final result should look like this:

Dark mode switch (Light mode)

Dark mode switch (dark mode)

Dark mode switch (dark mode)

Now, every time the user clicks the button, the entire layout changes from dark to light and vice versa. This is all the code you need to create a dark mode switcher using Tailwind CSS and Flowbite.

conclusion

I hope this tutorial will help you on your journey with Tailwind CSS and Flowbite when building a dark version of your site.