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

卡片添加过渡动画问题:hover背景仅淡入不淡出

解决Caption鼠标移出时背景无法平滑淡出的问题

问题根源

你的代码里,.caption初始状态没有设置background属性,仅在:hover状态下才添加背景渐变。鼠标移出时,background会直接从渐变值变回“无”,这个变化不在过渡监测范围内,所以无法触发淡出效果。另外还存在拼写错误:colour应该是标准CSS属性名color。

修正方案(简洁版)

只通过opacity控制淡入淡出,把背景渐变放在.caption初始状态:

.grid_content {
  max-width: 700px;
  margin: 0 auto;
  position: relative;
  overflow: hidden;
}

img {
  width: 100%;
  height: 100%;
  display: block;
}

.caption {
  position: absolute;
  z-index: 1;
  bottom: 0;
  padding: 30px;
  color: white; /* 修正拼写错误 */
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: opacity 1s; /* 仅过渡opacity属性 */
  background: linear-gradient(hsl(0, 0%, 100%, 0.1), hsl(0 0% 0% / 0.6));
}

h4 {
  font-family: var(--font-style-custom);
  letter-spacing: 3px;
}

p {
  margin: 5px;
}

h4,
p {
  position: relative;
  top: 85px;
}

.caption:hover {
  opacity: 1; /* hover时仅改变透明度 */
}

另一种方案(保留背景渐变过渡)

如果需要单独控制背景渐变的透明度变化,可以在初始状态设置全透明的同结构渐变:

.grid_content {
  max-width: 700px;
  margin: 0 auto;
  position: relative;
  overflow: hidden;
}

img {
  width: 100%;
  height: 100%;
  display: block;
}

.caption {
  position: absolute;
  z-index: 1;
  bottom: 0;
  padding: 30px;
  color: white; /* 修正拼写错误 */
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: all 1s ease; /* 过渡所有可动画属性 */
  /* 初始全透明渐变 */
  background: linear-gradient(hsl(0, 0%, 100%, 0), hsl(0 0% 0% / 0));
}

h4 {
  font-family: var(--font-style-custom);
  letter-spacing: 3px;
}

p {
  margin: 5px;
}

h4,
p {
  position: relative;
  top: 85px;
}

.caption:hover {
  opacity: 1;
  /* hover时显示半透明渐变 */
  background: linear-gradient(hsl(0, 0%, 100%, 0.1), hsl(0 0% 0% / 0.6));
}

效果说明

两种方案都能实现鼠标移入时背景平滑淡入,移出时平滑淡出的效果。第一种方案更简洁,通过透明度控制整体显隐;第二种方案可以单独调整背景渐变的透明度变化逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:50:29