CSS linear-gradient:线性渐变的方向与色标

CSS 的 linear-gradient() 会生成一张沿直线变化颜色的图像。background-image: linear-gradient(to right, yellow, red) 会让左侧的黄色过渡到右侧的红色。只接受单个颜色值的 background-color 无法使用这种图像。

指定线性渐变的方向

.box {
  background-image: linear-gradient(to right, yellow, red);
}
方向 从第一个颜色到最后一个颜色
to top 或 0deg 从下往上
to right 或 90deg 从左往右
to bottom 或 180deg 从上往下(默认)
to left 或 270deg 从右往左

省略方向时,第一个颜色在上方,最后一个颜色在下方。角度从向上的 0deg 起顺时针增加。to top right 这类角落关键字取决于元素框的宽高比。如果需要固定方向,可以写 45deg。参见 CSS Images · Linear Gradients。

运行四个渐变示例

把以下代码保存为 linear-gradient.html 并打开。四个色块展示了水平渐变、垂直渐变、限定范围的过渡和清晰分界,无需额外的图片文件。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>比较线性渐变</title>
  <style>
    body { margin: 20px; font: 16px/1.6 system-ui, sans-serif; color: #203348; }
    h1 { font-size: 24px; }
    main { max-width: 600px; display: grid; gap: 16px; }
    figure { margin: 0; }
    figcaption { margin-bottom: 6px; }
    .swatch { height: 85px; border: 1px solid #6e8295; border-radius: 6px; }
    .basic { background-image: linear-gradient(to right, yellow, red); }
    .vertical { background-image: linear-gradient(to bottom, yellow, red); }
    .stops { background-image: linear-gradient(to right, yellow 50%, red 60%, purple 100%); }
    .hard { background-image: linear-gradient(to right, #1768a5 50%, #11958e 50%); }
  </style>
</head>
<body>
<h1>比较线性渐变</h1>
<main>
  <figure><figcaption>向右:黄色到红色</figcaption>
    <div class="swatch basic" role="img" aria-label="背景从左侧的黄色过渡至右侧的红色"></div>
  </figure>
  <figure><figcaption>向下:黄色到红色</figcaption>
    <div class="swatch vertical" role="img" aria-label="背景从上方的黄色过渡至下方的红色"></div>
  </figure>
  <figure><figcaption>色标位置:50%、60%、100%</figcaption>
    <div class="swatch stops" role="img" aria-label="前半段保持黄色,随后经过红色过渡至紫色"></div>
  </figure>
  <figure><figcaption>两个颜色位于同一位置</figcaption>
    <div class="swatch hard" role="img" aria-label="蓝色和青绿色在中央直接相接"></div>
  </figure>
</main>
</body>
</html>

前两个色块在不同方向上使用相同的颜色。第三个色块在左半边保持黄色,之后经过红色过渡到紫色。最后一个色块在中央由蓝色直接变成青绿色。

调整纯色区域和过渡范围

在 yellow 50%, red 60%, purple 100% 中,百分比表示渐变线上达到该颜色的位置。0%~50% 是黄色,50%~60% 由黄色变成红色,60%~100% 由红色变成紫色。只把 red 60% 改成 red 80%,第一段过渡会加长,第二段会缩短。对比后恢复 60%。

如果省略全部位置,首尾两种颜色分别位于 0% 和 100%,其余色标等距排列。最后一个色块把两个色标都放在 50%,因此没有过渡距离。即使把第二个改为 40%,也会被修正到 50%。要移动分界线,需要同时修改两个位置。参见 CSS Images · Color Stop Fixup。

叠加渐变并排查背景不显示的问题

要在照片上叠加半透明渐变,请先在 background-image 中写带透明度的渐变,再写照片的 url(...)。第一层绘制在最上方。空元素中的渐变不可见时,先检查高度和内边距。后续的 background 简写可能重置背景图,请检查计算值。如果背景上有文字,还应确认它在明暗区域都清晰可读。参见 CSS Backgrounds · Layering。