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

如何为Modern-Card添加图片并保留悬停效果,且边框不遮挡图片?

带图片的Modern Card画廊实现方案

要解决图片替代背景导致悬停失效、边框遮挡图片的问题,我们可以通过调整卡片内部结构,将图片作为背景层,同时新增文字遮罩层实现悬停显示效果,具体修改如下:

核心修改思路

  • 将图片设为.card-info的背景,通过background-size: cover和border-radius保证图片完整显示且不被边框裁剪
  • 新增.text-overlay层,默认隐藏,悬停时触发显示深色半透明背景和自定义文字
  • 保留原卡片的渐变阴影与悬停动画效果

修改后的完整代码

CSS代码

.card {
  --background: linear-gradient(to left, #f7ba2b 0%, #ea5358 100%);
  width: 190px;
  height: 254px;
  padding: 5px;
  border-radius: 1rem;
  overflow: visible;
  background: var(--background);
  position: relative;
  z-index: 1;
}

.card::after {
  position: absolute;
  content: "";
  top: 30px;
  left: 0;
  right: 0;
  z-index: -1;
  height: 100%;
  width: 100%;
  transform: scale(0.8);
  filter: blur(25px);
  background: var(--background);
  transition: opacity .5s;
}

.card-info {
  width: 100%;
  height: 100%;
  border-radius: .7rem;
  position: relative;
  /* 替换为你的图片地址 */
  background-image: url('你的图片URL');
  background-size: cover;
  background-position: center;
}

.text-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: .7rem;
  background-color: rgba(0,0,0,0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.5s ease;
}

.card .title {
  font-weight: bold;
  letter-spacing: .1em;
  color: #f7ba2b;
}

/* 悬停效果 */
.card:hover::after {
  opacity: 0;
}

.card:hover .text-overlay {
  opacity: 1;
}

HTML代码

<div class="card">
  <div class="card-info">
    <div class="text-overlay">
      <p class="title">自定义文字</p>
    </div>
  </div>
</div>

关键细节说明

  1. 图片显示处理:.card-info的background-size: cover让图片按比例缩放充满容器,background-position: center保证图片居中,配合border-radius确保图片不会超出卡片圆角边框。
  2. 文字遮罩层:.text-overlay通过绝对定位覆盖在图片上方,默认透明隐藏,悬停时显示深色半透明背景与文字,不干扰原卡片的阴影动画。
  3. 风格统一:文字颜色沿用原卡片的渐变主色#f7ba2b,过渡动画时长设为0.5s,保证视觉效果流畅一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:05:20