css 实现前景渐变到背景的平滑混合

jaxagkaj  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(97)

我尝试在底层背景上创建一个纯CSS生成的彩虹渐变叠加。目标是让彩虹在中心完全不透明,在边缘附近逐渐褪色到完全透明,与背景无缝融合。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Smooth Fading of CSS-Generated Rainbow Gradient</title>
    <style>
        .container {
            position: relative;
            width: 500px;
            height: 300px;
            overflow: hidden;
            background: repeating-linear-gradient(45deg, #f00, #f00 10px, #0f0 10px, #0f0 20px);
        }

        .rainbow-overlay {
            position: absolute;
            top: 25%;
            left: 25%;
            width: 50%;
            height: 50%;
            background: linear-gradient(to right, violet, indigo, blue, green, yellow, orange, red);
            mask: 
                linear-gradient(transparent 10%, black 20%, black 80%, transparent 90%) /* vertical */ ,
                linear-gradient(to right, transparent 10%, black 20%, black 80%, transparent 90%) /* horizontal */;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="rainbow-overlay"></div>
    </div>
</body>
</html>

字符集
不幸的是,当前使用mask属性和linear-gradient的实现会导致两个梯度的并集或合并,而不是期望的交集。
有没有一种方法来实现这种平滑的褪色效果?任何见解或替代方法将不胜感激。

w8biq8rn

w8biq8rn1#

考虑mask-composite以避免合并

.container {
  position: relative;
  width: 500px;
  height: 300px;
  overflow: hidden;
  background: repeating-linear-gradient(45deg, #f00, #f00 10px, #0f0 10px, #0f0 20px);
}

.rainbow-overlay {
  position: absolute;
  inset: 25%;
  background: linear-gradient(to right, violet, indigo, blue, green, yellow, orange, red);
  --m:#0000 10%, #000 20% 80%, #0000 90%;
  mask: 
   linear-gradient(       var(--m)),
   linear-gradient(90deg, var(--m));
  -webkit-mask-composite: destination-in;
          mask-composite: intersect;
}

个字符

相关问题