Search code examples
svgalignmenttspan

How to align set of tspan elements by center?


I googled a lot of ways how to align set of tspan by center, but I need something else. I need to align the set of tspan elements by center and each element should be aligned by the left side with other elements.

On the picture below you can see what I'm trying to reach. enter image description here

JSFiddle

I tried to add one more tspan element as a wrapper for other and set to it text-anchor: middle, but it doesn't work.


Solution

  • For this I would use JavaScript to calculate the offset for the first tspan as half the difference of length between the two tspan elements

    let tspans = document.querySelectorAll("tspan");
    let offset = (tspans[1].getComputedTextLength() - tspans[0].getComputedTextLength())/2
    tspans[0].setAttributeNS(null,"dx", -offset)
    svg {
        border: solid 1px blue;
        font-family: monospace;
    }
    <svg viewBox = "0 0 400 100">
        <circle r="3" cx="200" cy="50" fill="red">
        </circle>
    
        <text y="50" text-anchor="middle"><!--
          --><tspan x="200" >First label</tspan><!--
          --><tspan x="200" dy="15">Second long long long label</tspan>
       </text>
    </svg>