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

如何为带背景模糊的透明Div创建渐变模糊边缘?

问题描述

我有一个透明div元素,通过组合使用backdrop-filter: blur()和rgba(255, 255, 255, 0)实现了模糊后方内容的效果,核心代码如下。我希望模糊效果不要在div的边框处突然终止,而是以渐变的方式淡出(类似带模糊属性的box-shadow,但阴影不可见,且模糊作用于后方内容)。目前能想到的唯一方案是在主div周围创建多个透明div,逐步增大尺寸并降低backdrop-filter: blur()的值来模拟效果,但这种方法过于繁琐,求更简洁的实现方式。

原代码

<div class="container">
  <div class="box">
  </div>
</div>
.box {
  background-color: rgb(255 255 255 / 0%);
  backdrop-filter: blur(10px);
  width: 300px;
  height: 100px;
}

body {
  background-image: url("https://i.pinimg.com/736x/ec/d8/34/ecd834e40fc5bbd91f3156a2f1823fca.jpg");
  background-size: cover;
}

html,
body {
  height: 100%;
  width: 100%;
}

.container {
  background-size: cover;
  align-items: center;
  display: flex;
  justify-content: center;
  height: 100%;
  width: 100%;
}

.box {
  border-radius: 5px;
  font-family: sans-serif;
  text-align: center;
  max-width: 50%;
  max-height: 50%;
  padding: 20px 40px;
}
解决方案

可以通过CSS mask(配合-webkit-mask做浏览器兼容)结合渐变效果,让backdrop-filter的模糊作用范围从元素中心向边缘平滑过渡,实现渐变淡出的效果。

修改后代码

<div class="container">
  <div class="box">
  </div>
</div>
.box {
  background-color: rgb(255 255 255 / 0%);
  backdrop-filter: blur(10px);
  width: 300px;
  height: 100px;
  /* 径向渐变遮罩:中心完全可见,边缘逐渐透明,实现四周模糊淡出 */
  mask: radial-gradient(circle, rgba(0,0,0,1) 60%, rgba(0,0,0,0) 100%);
  -webkit-mask: radial-gradient(circle, rgba(0,0,0,1) 60%, rgba(0,0,0,0) 100%);
  /* 若仅需要上下/左右单向渐变,改用线性渐变:
  mask: linear-gradient(to bottom, rgba(0,0,0,1) 50%, rgba(0,0,0,0) 100%);
  -webkit-mask: linear-gradient(to bottom, rgba(0,0,0,1) 50%, rgba(0,0,0,0) 100%);
  */
}

body {
  background-image: url("https://i.pinimg.com/736x/ec/d8/34/ecd834e40fc5bbd91f3156a2f1823fca.jpg");
  background-size: cover;
}

html,
body {
  height: 100%;
  width: 100%;
}

.container {
  background-size: cover;
  align-items: center;
  display: flex;
  justify-content: center;
  height: 100%;
  width: 100%;
}

.box {
  border-radius: 5px;
  font-family: sans-serif;
  text-align: center;
  max-width: 50%;
  max-height: 50%;
  padding: 20px 40px;
}

原理说明

  • mask属性控制元素的可见区域,渐变遮罩会让元素从中心到边缘的透明度逐步降低,而backdrop-filter仅作用于元素可见区域对应的后方内容,因此模糊效果会随遮罩的渐变同步淡出。
  • 调整渐变中的百分比参数(比如60%和100%)可以控制模糊过渡的范围和平滑度:百分比差值越大,过渡越平缓;差值越小,过渡越急促。
  • 由于部分浏览器对标准mask支持有限,添加-webkit-mask前缀以兼容webkit内核浏览器(如Chrome、Safari)。

内容的提问来源于stack exchange,提问作者Shady H. Bedda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 10:08:16