我正在尝试将渐变应用于 SVG rect
元素。
目前,我正在使用 fill
属性。在我的 CSS 文件中:
rect {
cursor: pointer;
shape-rendering: crispEdges;
fill: #a71a2e;
}
在浏览器中查看时,rect
元素具有正确的填充颜色。
但是,我想知道是否可以对这个元素应用线性渐变?
只需在 CSS 中使用您将在 fill
属性中使用的任何内容。当然,这需要您在 SVG 中的某处定义线性渐变。
这是一个完整的例子:
rect { 光标:指针;形状渲染:crispEdges;填充:网址(#MyGradient); }
2019答案
借助全新的 CSS 属性,您可以更灵活地使用变量,即 custom properties
.shape { 宽度:500px;高度:200px; } .shape .gradient-bg { 填充: url(#header-shape-gradient) #fff; } #header-shape-gradient { --color-stop: #f12c06; --color-bot:#faed34; }
只需为渐变中的每个 stop
设置一个命名变量,然后在 css 中根据需要进行自定义。您甚至可以使用 javascript 动态更改它们的值,例如:
document.querySelector('#header-shape-gradient').style.setProperty('--color-stop', "#f5f7f9");
基于 Finesse 所写的内容,这是一种针对 svg 并更改其渐变的更简单方法。
这是你需要做的:
为渐变元素中定义的每个色标分配类。定位 css 并使用普通类更改每个停靠点的停靠点颜色。赢!
使用类而不是 :nth-child
的一些好处是,如果您重新排列停靠点,它不会受到影响。此外,它使每个班级的意图变得清晰 - 您会想知道您是否需要在第一个孩子或第二个孩子上使用蓝色。
我已经在所有 Chrome、Firefox 和 IE11 上对其进行了测试:
.main-stop { 停止颜色:红色; } .alt-stop { 停止颜色:绿色; }
在此处查看可编辑的示例:https://jsbin.com/gabuvisuhe/edit?html,css,output
这是一个解决方案,您可以在其中添加渐变并仅使用 CSS 更改其颜色:
// 解决方案不需要 JS。它仅用于交互式演示。 const svg = document.querySelector('svg'); document.querySelector('#greenButton').addEventListener('click', () => svg.setAttribute('class', 'green')); document.querySelector('#redButton').addEventListener('click', () => svg.setAttribute('class', 'red')); svg.green stop:nth-child(1) { stop-color: #60c50b; } svg.green stop:nth-child(2) { stop-color: #139a26; } svg.red stop:nth-child(1) { stop-color: #c84f31; } svg.red stop:nth-child(2) { stop-color: #dA3448; }
谢谢大家,所有的准确答复。
在 shadow dom 中使用 svg,我在 svg 中添加了我需要的 3 个线性渐变,在 .我将 css 填充规则放在 web 组件上,继承 od 填充完成了这项工作。
fill
:fill: url(../js/gradient.svg#MyGradient);
。这是正确的方法吗?fill: linear-gradient (...)
怎么样?”的人。fill
需要一个围绕 CSS2<color>
类构建的<paint>
。换句话说,在我写这篇评论时,这个答案是目前通过 CSS 完成的唯一方法。您需要添加一个linearGradient
元素。最后,通过 SVG2 的 w3 工作草案,似乎对填充 css 规则的linear-gradient
的支持没有也可能不会进入规范。gradientTransform
属性)