SVG: why does external css override inline style for text?

一笑奈何 提交于 2019-11-28 08:58:33
Ben Lesh

Because in SVG, like HTML before it, styles trump attribute styling.

fill="red" below is NOT an "inline style", style="fill:green" IS an inline style.

<svg width="400" height="400">
  <text x="50" y="50" fill="red" style="fill:green">This will be green</text>
</svg>

Like wise, if you have a style defined outside, it will win.

<style>
  text { fill: lime; }
</style>
<svg width="300" height="300">
  <text x="50" y="40" fill="red">This will be lime</text>
</svg>

From the SVG specification

For user agents that support CSS, the presentation attributes must be translated to corresponding CSS style rules according to rules described in Precedence of non-CSS presentational hints ([CSS2], section 6.4.4), with the additional clarification that the presentation attributes are conceptually inserted into a new author style sheet which is the first in the author style sheet collection. The presentation attributes thus will participate in the CSS2 cascade as if they were replaced by corresponding CSS style rules placed at the start of the author style sheet with a specificity of zero. In general, this means that the presentation attributes have lower priority than other CSS style rules specified in author style sheets or ‘style’ attributes.

So you could use an inline style rather than a presentation attribute e.g.

.attr('style', 'fill : url(#theGradient)')

In my case it was as simple as replacing attr with style in the d3 chain:

.style('stroke', 'url(#gradient--min)')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!