4

For some reason the positioning of tspan elements is kept even if the tspan tag is closed.

<svg>
    <text x="50" y="50">1<tspan y="55" fill="red">2</tspan>3</text>
</svg>

http://jsfiddle.net/4fzqmeud/1/

Both numbers 2 and 3 are affected by the tspan positioning even though only 2 is inside the tspan. However, not so by the fill attribute. I find this an unexpected behavior.

I know I could use another tspan with y="50" around the 3. But this seems very cumbersome. Is there a way to "automatically" reset the position after the tspan without adding yet another tspan?

Daniel
  • 3,383
  • 4
  • 30
  • 61

3 Answers3

4

The tspan element's fill attribute is a presentation attribute which is a styling property. When you leave the tspan element, style settings fall back to the settings prior to entering the tspan.

The tspan element's x/y/dx/dy attributes are used to update the current text position. You would not want the current text position to fall back to its setting prior to entering the tspan. If it did then the x position would also reset causing the text following the tspan to horizontally overlap the text in tspan element.

The SVG specifications include a baseline-shift attribute which is designed to handle subscripts and superscripts. This is a presentation attribute and thus only affects the tspan like you want. This attribute can have values of "sub", "super", number, percent. For example

   <svg>
        <text x="50" y="50">1<tspan baseline-shift="sub" fill="red">2</tspan>3</text>
    </svg>

The baseline-shift attribute works in Chrome. Unfortunately, IE does not currently support the baseline-shift attribute. https://msdn.microsoft.com/en-us/library/gg558060(v=vs.85).aspx

To get the subscript to work in all browsers, it unfortunately looks like you have to use the cumbersome approach of using a second tspan around the 3 that you where trying to avoid.

Alexandr_TT
  • 13,635
  • 3
  • 27
  • 54
Bobby Orndorff
  • 3,265
  • 1
  • 9
  • 7
  • 3
    Thanks for the explanation. Add firefox to the browsers that do not support the `baseline-shift` attribute. https://bugzilla.mozilla.org/show_bug.cgi?id=308338 – Daniel Nov 15 '15 at 10:58
1

How about just specifying multiple y positions in the outer text element. You could also write y="50 50 50" and then set a y="55" in the tspan if you wanted.

<svg>
    <text x="50" y="50 55 50">1<tspan fill="red">2</tspan>3</text>
</svg>
Robert Longson
  • 118,664
  • 26
  • 252
  • 242
1

If you generate the SVG, you can reset the shift locally without having to know the surrounding elements by inserting a tspan with a zero-width space and the opposite offset:

<text>(x<tspan class="small" dy="3">1</tspan><tspan dy="-3">&#8203;</tspan>)</text>
Kaspar Etter
  • 3,155
  • 1
  • 14
  • 21