Search code examples
htmlcsssvgalignment

SVG text; align tspans to the left having text parent aligned to the right


Good day. Knowing x and y, I need to align the right edge of the multiline <text> to it. Problem is that content of the <tspan>s inside it should be aligned to the left. X and Y coordinates (with some offsets) serve as the starting coordinate for an <line>.

Smth like this:

enter image description here

Is there a possibility to achieve that behavior using svg's attributes and/or css?

I only came to what I can get the first <tspan>'s width via getBBox() and then use it as the line's start coordinate, by adding it to the x with text-align="start" on the parent <text>, but it's a runtime solution :(

Here's a simplified snippet:

<svg viewBox="0 0 500 500">
  <!-- Knowing x and y to translate -->
  <g transform="translate(200, 200)">
    <text
     x="0"
     y="0"
     fill="#000"
     text-anchor="end"
     dominant-baseline="hanging"
    >
     <tspan
      font-size="20"
      x="0"
     >
      Title
     </tspan>
     <tspan
      font-size="15"
      x="0"
      dy="20"
     >
      Subtitle
     </tspan>
     <tspan
      font-size="10"
      x="0"
      dy="15"
     >
      Description
     </tspan>
    </text>
  </g>
  <line
   stroke="#f11"
   stroke-width="3"
   x1="205"
   y1="210"
   x2="305"
   y2="210"
  />
</svg>


Solution

  • The answer is no.

    SVG doen't have any native automatic layout facilities that will allow you to do what you want. It expects you to know where exactly you want to place each line of text.

    You would need to use Javascript as you suggest.