Posts \ Change Image On Hover Using Tailwind

I was building an app where the admin user could receive messages from other users, and I wanted them to be able to star the important ones. This app used Tailwind, so I was curious if there was a way to do this. I found this Reddit post where a user shared an idea that worked:

<div class="group h-screen w-full bg-red-500">
  <div class="group-hover:hidden">img1</div>
  <div class="hidden group-hover:flex">img2</div>
</div>

You can see that the primary components here are:
  1. First, assigning the group class to the container, ie. the outside div (see the official Tailwind docs here). This allows you to add the 'group-' prefix to classes inside the container that apply when the container is interacted with (hovering, in this case).
  2. Second, alternately hiding and showing the images.

I translated this into Rails (using free Font Awesome icons):

<div class="group cursor-pointer flex w-4 flex-shrink-0 items-center justify-center text-sm font-medium text-white">
  <div class="group-hover:hidden">
    <%= fa_icon "star", class: "fa-solid text-yellow-500" %>
  </div>
  <div class="hidden group-hover:flex">
    <%= fa_icon "star", class: "text-lg fa-regular text-gray-500 opacity-20" %>
  </div>
</div>

You will notice that I have centered the icons inside of the container using flex. This is because the two icons I used appear to display at different heights, and the bottom of the containing element would raise up a pixel or two when I moused over them. YMMV, depending on which icons you choose.
imagesrailstailwindfont awesome