You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Tailwind CSS和HTML实现图片在div内部分隐藏及hover显示效果

解决Tailwind CSS卡片内图片溢出隐藏及悬停显示动画问题

核心解决思路

  • 给图片的父容器添加overflow-hidden属性,直接隐藏超出容器边界的内容
  • 为容器设置固定宽高,避免被溢出的图片撑开布局
  • 利用Tailwind的变换(transform)和过渡(transition)类,实现悬停时的平滑动画效果

修改后的完整代码

<!--Start card 1-->
<div class="group justify-items-center bg-white/10 mb-4 p-6 rounded-lg min-w-3 h-auto">
  <!--Title and date-->
  <div class="flex justify-between items-center mb-2">
    <h4 class="font-bold text-lg">MINI JAVA VIRTUAL MACHINE</h4>
  </div>

  <!--Subtitle-->
  <div class="mb-4">
    <h5 class="text-base text-white/70">Java</h5>
  </div>

  <!--Project description-->
  <div>
    <p class="font-light">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis ut lectus laoreet, imperdiet nunc tristique.</p>
  </div>

  <!--Project Github Button and Image Container-->
  <div class="flex items-center gap-4 mt-4">
    <button class="relative items-center gap-2 bg-white shadow-lg px-6 py-3 rounded-lg font-medium text-orange-600">
        View Project
      <span class="absolute inset-0 bg-white/20 opacity-0 group-hover:opacity-100 rounded-lg transition-opacity duration-300"></span>
    </button>

    <!-- 修改后的图片容器 -->
    <div class="w-32 h-32 overflow-hidden rounded-lg">
      <img class="w-full h-full object-cover rotate-12 transition-all duration-500 group-hover:rotate-0" src="img/projects_screenshots/root_project.png" alt="Preview project">
    </div>
  </div>
</div>
<!--Ends card 1-->

关键代码说明

  1. 卡片容器添加group类:让卡片内的子元素可以响应卡片的悬停状态,实现鼠标悬停整个卡片时触发图片动画
  2. 图片容器的核心设置:
    • w-32 h-32:固定容器尺寸,确保图片旋转后不会撑开容器
    • overflow-hidden:隐藏超出容器的图片部分,解决你遇到的溢出可见问题
    • rounded-lg:保持和卡片一致的圆角风格
  3. 图片的动画设置:
    • w-full h-full object-cover:让图片填满容器,避免拉伸变形
    • rotate-12:给图片添加初始旋转效果,模拟你描述的红色旋转区域
    • transition-all duration-500:让所有变换属性的变化平滑过渡,时长500ms
    • group-hover:rotate-0:鼠标悬停卡片时,图片旋转回0度,显示原本被裁剪的部分

自定义调整建议

  • 如果需要平移而非旋转来显示隐藏部分,可以把图片的初始类改成translate-x-4 translate-y-4 rotate-12,悬停类改成group-hover:translate-x-0 group-hover:translate-y-0
  • 可以调整rotate-*的数值、过渡时长duration-*,或者容器的宽高,适配你的具体设计需求

内容的提问来源于stack exchange,提问作者Emanuel Hosu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 21:02:40