DEV Community

Cover image for Revealing hidden elements when hovering a parent with Tailwind CSS
Mark Townsend
Mark Townsend

Posted on

Revealing hidden elements when hovering a parent with Tailwind CSS

Tailwind CSS makes it almost too easy these days. Add two classes: text-blue-500 hover:text-blue-700 and you have a perfectly styled link.

But what if you want to hide elements until the user hovers the mouse over a parent element? That type of UI requirement is fairly common for dashboard tables when you want to provide quick access to things without overwhelming the user with a lot of visual clutter.

Tailwind is capable of doing that with group hover. For this example, we're going to reach for a lesser used css attribute: visibility. The difference between visibility: hidden; and display: none; is the browser treats elements with their visibility set to hidden as still being present, but simply...invisible. Their space and padding are still respected, though, as if they were still present. Elements with their display set to none are essentially ignored from the markup. None of their spacing or padding impacts the page until they are visible again. We don't want elements jumping around when the user hovers over our element, so we'll be using visibility: hidden instead of display: none; for this example.

Consider the following HTML:

<div class="group">
   <p>Some content that is always visible.</p>
   <p class="invisible group-hover:visible">I am hidden until my parent is hovered!</p>
</div>
Enter fullscreen mode Exit fullscreen mode

You would probably expect this to work - but it won't. That's because Tailwind's group-hover doesn't support display types out of the box. But, with one line of code, we can easily make it work!

You can add this to your tailwind.config.js file:

...
variants: {
 extend: {
   visibility: ["group-hover"],
 },
},
...
Enter fullscreen mode Exit fullscreen mode

Now, it will work!

One thing to note: the visibility attribute cannot have transitions applied to it since it is an "on" or "off" field. If transitions is something you're after, consider using Tailwind's opacity.

Check out this Tailwind playground link to see group hover working with CSS's visibility class.

Discussion (1)

Collapse
ramk777stack profile image
RamK777-stack

Thanks you so much !!. useful content