Adding a tooltip is a great way to minimize less important information on the page. You can design a tooltip without using any JavaScript code. TailwindCSS group
are very helpful in these situations.
Designing a Tooltip with TailwindCSS Only
There are two steps to designing a tooltip in TailwindCSS. The first step is to create a container with group
class and the second is to add functionality that will display a tooltip only when a user hovers over the element.
Step 1: Adding Container and Tooltip Link
The following code adds a container for the tooltip with a simple span
element that will display the tooltip when being hovered. The group
class creates a group for the tooltip container.
1 2 3 4 5 6 7 |
<div class="group relative cursor-pointer py-2"> <span class="underline hover:cursor-pointer">Tooltip on the top </span> </div> |
Step 2: Adding Tooltip and Displaying When Hovered
The following code adds a new div
container with an invisible
class. This container will have the content for the tooltip. When a user hovers the span
used as a link the tooltip container will be visible because of the group-hover:visible
class.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<div class="group relative cursor-pointer py-2"> <div class="absolute invisible bottom-7 group-hover:visible w-40 bg-white text-black px-4 mb-3 py-2 text-sm rounded-md"> <p class=" leading-2 text-gray-600 pt-2 pb-2"> Tooltip description</p> <svg class="absolute z-10 bottom-[-10px] " width="16" height="10" viewBox="0 0 16 10" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M8 10L0 0L16 1.41326e-06L8 10Z" fill="white"/> </svg> </div> <span class="underline hover:cursor-pointer">Tooltip on the top </span> </div> |
You can check the working example of the tooltip and also see the screenshot below.
By using group
modifier in TailwindCSS, you can also create other useful components like dropdown menus.
Conclusion
You can design an effective tooltip component in TailwindCSS without using JavaScript. The group
modifier help to achieve this behavior with ease. You can use this tooltip in any project without ever worrying about the framework being used.