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

如何用纯CSS实现图片悬停灰盒上滑灰度化及移出反向动画?

解决鼠标移出时反向动画及灰度同步问题

你的核心问题是用animation无法自动处理hover移出时的反向过渡,改用transition就能完美解决——transition会在元素状态变化时自动应用过渡效果(包括hover和移出的反向过程),同时调整灰度层的背景位置,让它和盒子滑动同步。

修改后的完整代码

HTML

<div class="wrapper">
  <img src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg" />
  
  <div class="hover">
    <div class="gray-image"></div>
    <div class="slide-box">
      <div class="text">
          <span>This is the title</span>
      </div>
    </div>
  </div>
</div>

CSS

.wrapper {
  position: relative;
  width: 600px;
  height: 375px;
  overflow: hidden; /* 防止元素溢出容器 */
}

.wrapper img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保证图片比例适配容器 */
}

.wrapper .hover {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 2;
  width: 100%;
  height: 100px;
  transition: height 1s ease; /* 核心:height变化的过渡动画,hover/移出自动反向 */
}

.wrapper .hover .gray-image {
  width: 100%;
  height: 100%;
  background-image: url('https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: bottom 0 left 0;
  filter: grayscale(100%);
  -webkit-filter: grayscale(100%);
  transition: background-position 1s ease; /* 灰度层背景位置同步过渡 */
  position: absolute;
  top: 0;
  left: 0;
}

.wrapper .hover .slide-box {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
}

.wrapper .hover .text {
  color: #FFF;
  text-align: center;
  width: 100%;
  height: 100px;
  background-color: rgba(89, 89, 89, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 鼠标悬停状态 */
.wrapper:hover .hover {
  height: 100%; /* 盒子上滑铺满整个容器 */
}

.wrapper:hover .hover .gray-image {
  background-position: top 0 left 0; /* 灰度层同步上移,覆盖整个图片 */
}

关键改动说明

  1. 替换animation为transition:
    给.hover添加transition: height 1s ease;,hover时height从100px过渡到100%,移出时自动反向过渡回100px,无需额外定义反向动画。
  2. 灰度层同步过渡:
    给.gray-image添加transition: background-position 1s ease;,hover时将背景位置从bottom 0改为top 0,让灰度区域随着盒子上滑逐步覆盖整个图片,移出时反向恢复。
  3. 移除display:none:
    display属性无法触发过渡效果,让.hover默认显示,初始height为100px,保证过渡动画正常触发。
  4. 优化布局稳定性:
    给.wrapper设置固定宽高和overflow: hidden,用object-fit: cover保证图片比例正确,将.slide-box绝对定位在底部,确保文本盒子始终停留在最下方。

这样就能实现完整效果:鼠标悬停时灰色盒子上滑,覆盖区域逐步变灰;鼠标移出时盒子下滑,灰度效果逐步消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 17:43:23