stop-color

Baseline 已廣泛支援

該特性已非常成熟,可在多種裝置和瀏覽器版本上使用。自 2017 年 4 月以來,它已在各大瀏覽器上可用。

stop-color CSS 屬性定義了在漸變中用於 SVG <stop> 元素的顏色。如果存在,它會覆蓋元素的 stop-color 屬性。

注意: stop-color 屬性僅適用於巢狀在 <svg> 中的 <stop> 元素。它不適用於其他 SVG、HTML 或偽元素。

語法

css
/* <color> values */
stop-color: red;
stop-color: hsl(120deg 75% 25% / 60%);
stop-color: currentColor;

/* Global values */
stop-color: inherit;
stop-color: initial;
stop-color: revert;
stop-color: revert-layer;
stop-color: unset;

<color>

填充顏色。可以是任何有效的 CSS <color> 值。

正式定義

初始值black
應用於<stop> 元素在 <svg>
繼承性
計算值同指定值
動畫型別離散

正式語法

stop-color = 
<color>

示例

定義 SVG 漸變的顏色停止點

此示例演示了 stop-color 的基本用法,以及 CSS stop-color 屬性如何優先於 stop-color 屬性。

HTML

我們有一個 SVG,其中包含三個 <rect> 方塊和三個 <linearGradient> 元素。每個漸變都有四個 <stop> 元素,建立從黑色到白色,然後從白色到灰色的漸變;它們之間唯一的區別是 id 值。

html
<svg viewBox="0 0 264 100" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="myGradient1">
      <stop offset="25%" stop-color="black" />
      <stop offset="40%" stop-color="white" />
      <stop offset="60%" stop-color="white" />
      <stop offset="75%" stop-color="#333333" />
    </linearGradient>
    <linearGradient id="myGradient2">
      <stop offset="25%" stop-color="black" />
      <stop offset="40%" stop-color="white" />
      <stop offset="60%" stop-color="white" />
      <stop offset="75%" stop-color="#333333" />
    </linearGradient>
    <linearGradient id="myGradient3">
      <stop offset="25%" stop-color="black" />
      <stop offset="40%" stop-color="white" />
      <stop offset="60%" stop-color="white" />
      <stop offset="75%" stop-color="#333333" />
    </linearGradient>
  </defs>
  <rect x="2" y="10" width="80" height="80" fill="url('#myGradient1')" />
  <rect x="92" y="10" width="80" height="80" fill="url('#myGradient2')" />
  <rect x="182" y="10" width="80" height="80" fill="url('#myGradient3')" />
</svg>

CSS

我們包含一個 strokestroke-width 來勾勒矩形。我們使用 stop-color 屬性定義每個漸變中第一個和最後一個停止點的顏色,覆蓋它們的 stop-color 屬性值。展示了各種 CSS <color> 語法。

css
rect {
  stroke: #333333;
  stroke-width: 1px;
}

#myGradient1 {
  stop:first-of-type {
    stop-color: #66ccff;
  }
  stop:last-of-type {
    stop-color: #f4aab9;
  }
}
#myGradient2 {
  stop:first-of-type {
    stop-color: yellow;
  }
  stop:last-of-type {
    stop-color: purple;
  }
}
#myGradient3 {
  stop:first-of-type {
    stop-color: hsl(0deg 90% 50%);
  }
  stop:last-of-type {
    stop-color: hsl(20deg 60% 50%);
  }
}

結果

規範

規範
Scalable Vector Graphics (SVG) 2
# StopColorProperty

瀏覽器相容性

另見