SVG attributes beaten by CSS&style in priority?

Viewed 1134

I have SVG line with specified stroke attribute.

<line class="myLine" stroke="red" x1="40" x2="200" y1="100" y2="100" stroke-width="5" />

And there is a CSS class that has stroke value in it:

line.myLine
{
  stroke:green
}

How come CSS class actually takes priority over explicit svg attribute and the line renders as green???

At the same time if I add style attribute with stroke in it, then style overrides css class & stroke svg attribute. So the priorities order is the following:

  1. style attribute
  2. css class
  3. svg attribute

How come SVG attribute is the lowest priority???

https://jsfiddle.net/pmunin/6j5woyry/

2 Answers

A long read from the standard: https://www.w3.org/TR/SVG/styling.html#UsingPresentationAttributes

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.

Hopefully this isn't too late, but this helped me actually understand the issue:

Attributes on SVG elements are at the lowest level of priority, as mentioned in the attribute spec: https://www.w3.org/TR/SVG/styling.html#PresentationAttributes

This means if you want a particular attribute on a specific element, add it to the style="[...]" attribute for the element such that it has the highest specificity and therefore the highest priority.

For example, if you want to override stroke as in the original example, use style="stroke: red;" instead of stroke="red". If you're using a library such as D3, make sure you're using .style() instead of .attr() to set high-priority styles.

Hope that helps others.

Related