Search code examples
svgtexttspan

SVG: How to remove the offset from tspan for multiline text with text-anchor set to middle?


I have some multi-line text and I am using <text> and <tspan> to handle this. I want each line to be centered, so I am using in the main <text> tag text-anchor="middle". However, even with dx=0, the entire block is still shifted by the total length text.

How can I do multi-lined <tspan> centered SVG text?

e.g.

<text text-anchor="middle" font-size="12px">
    This would normally be centered
    <tspan>
        this should be too.
    </tspan>
</text>

Solution

  • You could specify the same x for the tspan as the text e.g.

    <svg>
    <text x="100" y="30" text-anchor="middle" font-size="12px">
        This would normally be centered
        <tspan x="100" dy="30">
            this should be too.
        </tspan>
    </text>
    </svg>

    or use a transform and set x="0" for the tspan...

        <svg>
        <text transform="translate(100, 30)" text-anchor="middle" font-size="12px">
            This would normally be centered
            <tspan x="0" dy="30">
                this should be too.
            </tspan>
        </text>
        </svg>