发布于 2026-01-06 2 阅读
0

使用 Tailwind CSS 实现群组悬停效果

使用 Tailwind CSS 实现群组悬停效果

图片替代文字
当我遇到鼠标悬停时每个元素的行为都不同的问题时,我甚至不知道该怎么称呼它,也不知道该如何搜索。尝试了几个关键词后,我终于明白了是怎么回事,并尝试从头开始编写 CSS。但要为每个子元素维护颜色背景边框色以及其他各种样式,实在太繁琐了。后来我Tailwind CSS
中 找到了Group-hover组件,使用起来非常方便。只需在父元素中 添加group ,然后在所有需要设置悬停样式的子元素中添加group-hover:,其他样式就都自动处理了。 代码大概是这样的:



      <div className=' flex h-screen justify-center items-center'>
        <div className='group text-xl'>
          <strong className='group-hover:text-red-500'>Hover on me </strong>
          <strong className='group-hover:text-green-500'>the texts will be </strong>
          <strong className='group-hover:text-blue-500'>of different colors</strong>
        </div>
      </div>

Enter fullscreen mode Exit fullscreen mode

除非要对某些插件应用组悬停功能,而该插件需要在配置文件的变体中启用,否则tailwind.config.js文件不需要任何配置。

文章来源:https://dev.to/heyitsaastha/group-hover-using-tailwind-css-4a2l