纯Tailwind CSS实现图片缩放交互效果的方案咨询
问题
需要实现如下UI效果:
- 图片底部叠加可点击标题
- 鼠标悬停图片或标题区域时,图片均会放大
目前已通过自定义CSS完成功能,但希望改用纯Tailwind CSS实现。此前尝试的纯Tailwind方案仅能在悬停图片时触发缩放,由于标题需要保持可点击状态,无法给标题添加pointer-events-none,因此悬停标题时图片不会缩放,求可行的纯Tailwind解决方案。
现有自定义CSS实现代码
component.tsx
<div className="card relative h-full w-full overflow-hidden rounded-md"> <div style={{ backgroundImage: `url(${post.slug})` }} className="image relative w-full h-full bg-cover bg-center transition-transform duration-700 ease-out" /> <div className="absolute bottom-0 w-full text-center text-white"> <Link href={post.slug} className="block p-2"> {post.title} </Link> </div> </div>
global.css
.card:hover .image { transform: scale(1.1); }
尝试过的纯Tailwind代码(无效)
<div className="relative h-full w-full overflow-hidden rounded-md hover:[&>div:first-child]:scale-110"> <div style={{ backgroundImage: `url(${post.slug})` }} className="relative w-full h-full bg-cover bg-center transition-transform duration-700 ease-out" /> <div className="absolute bottom-0 w-full text-center text-white"> <Link href={post.slug} className="block p-2"> {post.title} </Link> </div> </div>
解决方案
核心思路是利用Tailwind的组状态功能,让最外层容器统一监听hover状态,无论鼠标悬停在容器内的图片还是标题上,都触发图片缩放:
<div className="relative h-full w-full overflow-hidden rounded-md group"> <div style={{ backgroundImage: `url(${post.slug})` }} className="w-full h-full bg-cover bg-center transition-transform duration-700 ease-out group-hover:scale-110" /> <div className="absolute bottom-0 w-full text-center text-white"> <Link href={post.slug} className="block p-2"> {post.title} </Link> </div> </div>
代码说明
- 给最外层容器添加
group类,开启Tailwind的组状态监听 - 给图片元素添加
group-hover:scale-110,表示当父容器(group)处于hover状态时,图片执行缩放动画 - 标题保持可点击状态,鼠标悬停标题时,父容器的hover状态会正常触发(子元素默认不会阻止父元素的hover事件传递),因此图片会同步缩放
该方案完全基于纯Tailwind实现,无需自定义CSS,同时满足所有需求。
内容的提问来源于stack exchange,提问作者Ramesh-X
相关产品推荐
相关产品推荐

