如何在页面全局 CSS 文件中定义 SVG 渐变
How to define SVG gradient in page-global CSS file
在我的 HTML 页面上,我有一些 JavaScript 代码可以生成 SVG 元素并将它们添加到 HTML 页面。
目前,这些 SVG 的所有样式(填充颜色等)都在 页面的 CSS 中定义。这样 SVG 就可以使用相同的 CSS 类 而我只需要定义一次属性。
现在我希望这些 SVG 使用线性渐变。然而,MDN 似乎没有透露任何在页面全局 CSS 中定义线性渐变的方法。所以我的问题如下:
- 有没有办法在页面全局中定义线性渐变CSS?
- 如果不是,并且如果我要在每个 SVG 中使用
<linearGradient>
元素定义线性渐变,它们是否可以具有相同的 ID? fill: url(#my-gradient)
能否正确访问相关 SVG 中的渐变?
- 如果不是,我如何在任何 SVG 之外声明一个带有 ID 的
<linearGradient>
?是否可以有一个仅定义渐变的“虚拟”SVG,并且 CSS 可以通过其 ID 引用该渐变?
Is there any way to define the linear gradient in the page-global CSS?
没有。您可以使用 CSS 设置某些 linearGradient
属性的样式,但不能定义渐变本身。
If not, and if I were to define the linear gradient using a element within each SVG, is it OK for them to have the same ID?
如果你的意思是多个linearGradient具有相同的id,那么编号id属性必须是唯一的。
If not, how can I declare a single with an ID outside of any SVG? Is it possible to have a “dummy” SVG that defines only the gradient and the CSS can refer to that gradient by its ID?
您可以在一个内联 SVG 中定义一个 linearGradient 并从另一个访问它。您可以使用 CSS 指定渐变。
svg rect {
fill: url(#mygradient);
}
#mygradient stop.start-color {
stop-color: red;
}
#mygradient stop.end-color {
stop-color: blue;
}
<svg width="0" height="0">
<defs>
<linearGradient id="mygradient">
<stop offset="0" class="start-color"/>
<stop offset="1" class="end-color"/>
</linearGradient>
</defs>
</svg>
<svg>
<rect width="300" height="150"/>
</svg>
在我的 HTML 页面上,我有一些 JavaScript 代码可以生成 SVG 元素并将它们添加到 HTML 页面。
目前,这些 SVG 的所有样式(填充颜色等)都在 页面的 CSS 中定义。这样 SVG 就可以使用相同的 CSS 类 而我只需要定义一次属性。
现在我希望这些 SVG 使用线性渐变。然而,MDN 似乎没有透露任何在页面全局 CSS 中定义线性渐变的方法。所以我的问题如下:
- 有没有办法在页面全局中定义线性渐变CSS?
- 如果不是,并且如果我要在每个 SVG 中使用
<linearGradient>
元素定义线性渐变,它们是否可以具有相同的 ID?fill: url(#my-gradient)
能否正确访问相关 SVG 中的渐变? - 如果不是,我如何在任何 SVG 之外声明一个带有 ID 的
<linearGradient>
?是否可以有一个仅定义渐变的“虚拟”SVG,并且 CSS 可以通过其 ID 引用该渐变?
Is there any way to define the linear gradient in the page-global CSS?
没有。您可以使用 CSS 设置某些 linearGradient
属性的样式,但不能定义渐变本身。
If not, and if I were to define the linear gradient using a element within each SVG, is it OK for them to have the same ID?
如果你的意思是多个linearGradient具有相同的id,那么编号id属性必须是唯一的。
If not, how can I declare a single with an ID outside of any SVG? Is it possible to have a “dummy” SVG that defines only the gradient and the CSS can refer to that gradient by its ID?
您可以在一个内联 SVG 中定义一个 linearGradient 并从另一个访问它。您可以使用 CSS 指定渐变。
svg rect {
fill: url(#mygradient);
}
#mygradient stop.start-color {
stop-color: red;
}
#mygradient stop.end-color {
stop-color: blue;
}
<svg width="0" height="0">
<defs>
<linearGradient id="mygradient">
<stop offset="0" class="start-color"/>
<stop offset="1" class="end-color"/>
</linearGradient>
</defs>
</svg>
<svg>
<rect width="300" height="150"/>
</svg>