Onjsdev

Share


How To Create A Toggle Switch With TailwindCSS


By onjsdev

Jan 4th, 2024

A Toogle Switch is useful component in any application. Let's see how to create it using Tailwind CSS.

HTML Structure

Let's start by building the HTML structure for the toggle switch:

<label>
  <input type="checkbox" value="" />
  <div></div>
</label>

To break down the HTML code:

  • <label> element that acts as a container for our toggle switch
  • Inside the label, we have an <input> element of type "checkbox."
  • <div> element represents the visual part of our toggle switch. It is styled using Tailwind CSS classes for size, background color, focus effects, and more.

CSS Styling

Now, let's style the HTML elements above to create a toggle switch. Class list for the switch is quite long. However, we will explain the purpose of the each of them.

Here is the final version of the switch with its style.

 <label class="relative inline-flex items-center cursor-pointer">
        <input type="checkbox" value="" class="sr-only peer" />
        <div class="w-11 h-6 peer bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full  peer-checked:after:translate-x-full  after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border after:rounded-full after:h-5 after:w-5 after:transition-all  peer-checked:bg-blue-600"></div>
 </label>

Let's also break down the TailwindCSS style classes:

  • w-11 h-6 bg-gray-200: These classes define the width, height, and background color of the toggle switch.
  • Classes with the after prefix style the knob's appearance, including background color, border, size, and transition effects.
  • peer represent the sibling element which is input in this case. For example, peer-checked-translate-x-full means when input is checked, knob will move in x axis.

Conclusion

In this article, we have showed how to create a toggle switch with TailwindCSS. With these steps, you should have a basic theme toggle switch in your application. Now, you can expand theme toggling functionality and customize the styles further.

If you want to learn more about Tailwind CSS, then you can take a look at the following articles:

Thank you for reading