Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG: text indentation/space issue on last tspan in group of tspan elements

Tags:

html

text

svg

tspan

This code inserts white space on the last of a group of tspan elements, causing the last line of text to fall out of alignment (on the x-axis).

If you add/remove tspan elements from the group, the last line of text always exhibits this behavior.

What's causing this extra white space or indentation?

Code pen: https://codepen.io/anon/pen/vvyZaj

<svg id="textBox1" x="0" y="0" width="200" height="300">
  <rect class="background" x="0%" y="0%" width="100%" height="100%" fill="gray" />

  <text class="textLines" x="0" y="0">
        <tspan x="100" dy="0.6em" text-anchor="middle" dominant-baseline="middle">tspan line 0</tspan>
        <tspan x="100" dy="1.2em" text-anchor="middle" dominant-baseline="middle">tspan line 1</tspan>
        <tspan x="100" dy="1.2em" text-anchor="middle" dominant-baseline="middle">tspan line 2</tspan>
  </text>
</svg>
like image 618
Crashalot Avatar asked Feb 02 '26 10:02

Crashalot


1 Answers

Whitespace collapses in SVG and HTML by default, i.e. multiple contiguous whitespace converts to a single space within text or no space at all at the beginning and the end.

You have a complicated layout though you don't realise it where the text in the <tspan> elements has various CSS properties that affect its alignment both vertically and horizontally but the whitespace surrounding it does not. That whitespace will however affect layout.

The simplest thing to do would be to remove all the whitespace that's within the <text> elements that's not also within a <tspan> element.

like image 167
Robert Longson Avatar answered Feb 05 '26 04:02

Robert Longson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!