记录 CSS 常见渐变

29 阅读2分钟

CSS 常见渐变主要有 6 种:

类型作用
linear-gradient线性渐变,按钮/背景最常用
radial-gradient径向渐变,适合光晕、聚光灯
conic-gradient锥形渐变,适合饼图、扫光边框
repeating-linear-gradient重复线性渐变,适合条纹
repeating-radial-gradient重复径向渐变,适合波纹/圆环
repeating-conic-gradient重复锥形渐变,适合刻度盘/放射纹

核心区别:

/* 1. 线性渐变:沿一条线 */
background: linear-gradient(135deg, red, blue);

/* 2. 径向渐变:从中心向外 */
background: radial-gradient(circle at center, red, blue);

/* 3. 锥形渐变:围绕中心旋转 */
background: conic-gradient(from 0deg, red, yellow, green, blue, red);

radial-gradientconic-gradient 存在中心点(默认中心点)

background: radial-gradient(circle at 30% 40%, red, blue);

background: conic-gradient(
  from 0deg at 30% 40%,
  red,
  yellow,
  blue
);

进阶想法

  • 手电筒光效果(Spotlight)

<div class="flashlight"></div>
.flashlight {
  position: fixed;
  inset: 0;
  pointer-events: none;
  background: radial-gradient(
    circle at 50% 50%,
    rgba(255,255,255,0.3) 0px,
    rgba(255,255,255,0.1) 80px,
    rgba(0,0,0,0.6) 200px,
    rgba(0,0,0,0.9) 400px
  );
}
document.addEventListener('mousemove', e => {
  const x = e.clientX;
  const y = e.clientY;

  document.querySelector('.flashlight').style.background =
    `radial-gradient(circle at ${x}px ${y}px,
      rgba(255,255,255,0.3) 0px,
      rgba(255,255,255,0.1) 80px,
      rgba(0,0,0,0.6) 200px,
      rgba(0,0,0,0.95) 400px
    )`;
});
  • 瞄准镜效果(Scope)

<div class="scope">
  <div class="crosshair"></div>
</div>
.scope {
  position: fixed;
  inset: 0;

  background: radial-gradient(
    circle at center,
    transparent 120px,
    rgba(0,0,0,0.8) 140px
  );
}

.crosshair::before,
.crosshair::after {
  content: "";
  position: absolute;
  background: rgba(255,255,255,0.8);
}

.crosshair::before {
  width: 2px;
  height: 100%;
  left: 50%;
  transform: translateX(-50%);
}

.crosshair::after {
  height: 2px;
  width: 100%;
  top: 50%;
  transform: translateY(-50%);
}
  • 多光源

background:
  radial-gradient(circle at 30% 40%, rgba(255,255,255,0.3), transparent),
  radial-gradient(circle at 70% 60%, rgba(0,200,255,0.2), transparent);
  • 呼吸光

@keyframes pulse {
  0% { background-size: 200px 200px; }
  100% { background-size: 260px 260px; }
}