Search code examples
angularsvgtextjustify

How to justify SVG text to the right?


I am using SVG to create some tables and put some text inside them. I can controll the placement of the text with SVG coordinates, but the text length is variable as it comes from some data. There is some way to get the length of the text or some other tool to justify it to the right?


Solution

  • align right

    Place your text on a textPath, set pathLength=100

    https://developer.mozilla.org/en-US/docs/Web/SVG/Element/textPath

    startoffset and text-anchor take care of positioning

    play with lower startoffset to add right-padding

    Note! Defining the path on the textPath itself is only supported in FireFox

    <svg viewbox="0 0 200 50">
      <path id="P" pathLength="100" d="M0 25h200" stroke="blue"/>
      <text>
        <textPath href="#P" 
                  startoffset="100" text-anchor="end" 
                  dominant-baseline="middle"
                  fill="green" font-size="14px">Right aligned</textPath>
      </text>
    </svg>