How to build a tooltip with Tailwind CSS
In this post, weâre going to create a basic tooltip using Tailwind CSS that looks like this:
This method requires no external libraries or packages.
Hereâs the simplified code for that tooltip, without opinionated styling (background color, font size, etc):
<!-- Padding so you can see the tooltip. -->
<div class="p-10">
<div class="group relative w-max">
<button>Click me!</button>
<span
class="pointer-events-none absolute -top-7 left-0 w-max opacity-0 transition-opacity group-hover:opacity-100"
>
This is a button.
</span>
</div>
</div>
- The tooltip is absolutely positioned above the button using the class
-top-7
. You can mess with the value7
to move its position. - The whole thing is wrapped in the
group
class, which allows us to usegroup-hover:
â that means that when anything in the âgroupâ is hovered (the âgroupâ only includes the button, because the span is absolutely positioned outside of the group), the span will show. - I used opacity instead of
hidden
andgroup-hover:block
so we could have a nice fade-in withtransition-opacity
. - I used
pointer-events-none
on the tooltip, which means that the mouse cannot interact with it at all â the tooltipâs text canât be selected, etc.- If you want the tooltipâs text to be selectable, you still want to use this class when the tooltip isnât showing so the text isnât selectable while invisible. In that case, use the two classes
pointer-events-none group-hover:pointer-events-auto
.
- If you want the tooltipâs text to be selectable, you still want to use this class when the tooltip isnât showing so the text isnât selectable while invisible. In that case, use the two classes
- I used
w-max
multiple times so elements, like the buttonâs area that can be hovered, would be exactly the necessary width.
If you want to play with this code in a sandbox, including the slightly styled version in the video above, I created a sandbox on Tailwind Play.