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

如何使用CSS为body设置的背景图片添加彩色遮罩效果

方案1:多重背景叠加(无需额外DOM,实现最简单)

直接修改原有background-image属性,在背景图前叠加半透明彩色渐变作为遮罩即可:

body {
  /* 半透明渐变需写在图片地址前,层级更高,会叠加在背景图上方 */
  background-image : linear-gradient(rgba(30, 70, 180, 0.45), rgba(30, 70, 180, 0.45)), url("bg.png");
  background-repeat: no-repeat;
  background-attachment: fixed;  
  background-size: cover;
}

你可以自行修改rgba参数调整遮罩效果:前三个值为RGB色值控制遮罩颜色,第四个值为透明度,取值范围0-1,数值越大遮罩越不透明。


方案2:伪元素实现(适合复杂遮罩控制场景)

如果后续需要给遮罩加动画、或者需要更灵活的层级控制,可以用body伪元素实现遮罩:

body {
  position: relative;
  min-height: 100vh;
  margin: 0;
  background-image : url("bg.png");
  background-repeat: no-repeat;
  background-attachment: fixed;  
  background-size: cover;
}
/* 生成遮罩层 */
body::after {
  content: "";
  position: absolute;
  /* 等同于top、right、bottom、left全设为0,铺满整个页面 */
  inset: 0;
  background-color: rgba(30, 70, 180, 0.45);
  /* 层级设为-1,避免遮罩盖住页面文字、图片等内容 */
  z-index: -1;
}

如果需要渐变彩色遮罩,把background-color替换为对应linear-gradient参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:45:03