Tailwind CSS:在图像悬停时显示文本

14

如何使用Tailwind CSS在图像悬停时显示文本:在图像悬停上显示文本?

这是我的图片吗?我希望当用户悬停在图像上时显示文本“哺乳动物”?

<img src="/img/cat/categories/mammals.png" alt="mammals" class="max-w-full max-h-full">

2
alt 属性替换为 title - dfvc
4个回答

22

我更喜欢使用相对定位和绝对定位,因为这使我有更多的工作选项。查看此代码在悬停时显示文本

<div class="w-64 h-64 bg-red-100 relative">
  <div class="absolute inset-0 bg-cover bg-center z-0" style="background-image: url('https://upload.wikimedia.org/wikipedia/en/3/3c/JumanjiTheNextLevelTeaserPoster.jpg')"></div>
  <div class="opacity-0 hover:opacity-100 duration-300 absolute inset-0 z-10 flex justify-center items-center text-6xl text-white font-semibold">Dwayne</div>
</div>

我将展示标题在悬停不透明度上。这在Tailwind CSS中可能吗? - ExpertWeblancer
@ExpertWeblancer 当然可以。请为此创建一个单独的问题。这样它就不会隐藏在某个线程的评论中,使其他人更容易跟进。 - Digvijay

13
你可以在你的img标签中使用title属性。
<img src="/img/cat/categories/mammals.png" alt="mammals" class="max-w-full max-h-full" title="mammals">

8
另一个想法是使用 group-hover 类。

.as-console-wrapper {
  display: none !important;
}
<script src="https://cdn.tailwindcss.com"></script>

<div class="w-64 bg-red-100 relative group">
  <img src="https://upload.wikimedia.org/wikipedia/en/3/3c/JumanjiTheNextLevelTeaserPoster.jpg" />
  <div class="opacity-0 group-hover:opacity-100 duration-300 absolute inset-x-0 bottom-0 flex justify-center items-end text-xl bg-gray-200 text-black font-semibold">Dwayne</div>
</div>

{{链接1:演示}}


7

请使用此代码,它可以很好地工作

  <div class="relative ">
    <a class="absolute inset-0 z-10 bg-white text-center flex flex-col items-center justify-center opacity-0 hover:opacity-100 bg-opacity-90 duration-300">
      <h1  class=tracking-wider >Title</h1>
      <p  class="mx-auto">Description</p>
      </a>
    <a href="#" class="relative">
        <div class="h-48 flex flex-wrap content-center">
            <img src="/image_url" class="mx-auto  " alt="">
        </div>
    </a>
  </div>

enter image description here


1
我根据我的情况对这个解决方案进行了调整,在React中将文本和图像作为props动态传递,经过一些“适应性”工作后,它非常好用。 - Carmine Tambascia
1
我修改了解决方案,使其能够传递可点击的SVG图标和相应的文本标签。 - Julio Spinelli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接