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

如何为background-image创建遮罩或裁剪渐变效果

问题根因

你现在出现渐变铺满整个容器的核心原因是:多个背景层默认继承容器全局的背景配置,你当前没有给渐变层单独配置和背景图一致的尺寸、位置规则,导致渐变层铺满了整个.card容器,而背景图因为未铺满容器,就出现了渐变超出图片范围的情况。同时你代码中rgba的色值写了256,属于不规范写法,rgba色值范围为0-255,建议修正为255。

解决方案

利用CSS多背景层支持单独配置规则的特性,给渐变层和图片层分别设置相同的background-size、background-repeat、background-position,让渐变的显示范围和背景图完全重合即可。

修正后的完整代码

.container{
  background-color:black;
  height:1200px;
}

.card {
  width: 100%;
  height: 100%;
  border: 1px solid red;
  /* 背景层顺序:渐变层在前,图片层在后 */
  background-image: linear-gradient(to right, rgba(255, 0, 0, 0.52), rgba(0, 255, 0, 0.73)), url('https://i.ibb.co/BPjySrv/card.png');
  /* 按背景层顺序分别配置重复规则 */
  background-repeat: no-repeat, no-repeat;
  /* 按背景层顺序统一设置显示尺寸,需要固定尺寸可替换contain为具体数值 */
  background-size: contain, contain;
  /* 按背景层顺序统一设置对齐位置 */
  background-position: left top, left top;
}

可选方案:mask裁剪(适用透明渐变裁剪场景)

如果你需要实现的是图片边缘渐隐到容器背景的裁剪效果,可以用mask-image属性实现:

.card {
  width: 100%;
  height: 100%;
  border: 1px solid red;
  background-image: url('https://i.ibb.co/BPjySrv/card.png');
  background-repeat: no-repeat;
  background-size: contain;
  background-position: left top;
  /* 渐变裁剪规则:黑色不透明区域显示图片,透明区域隐藏图片 */
  mask-image: linear-gradient(to right, rgba(0,0,0,1), rgba(0,0,0,0));
  -webkit-mask-image: linear-gradient(to right, rgba(0,0,0,1), rgba(0,0,0,0));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 21:45:00