Search code examples
svgpositiontspan

Alignment of tspans inside text


I seem to not be able to solve this issue despite reading similar issues on SO. I would like my legend and sublegend (so the two tspans inside the text) to align on the x-attribute (So Austin and Detail sublegend should start at the same x position:

enter image description here

https://jsfiddle.net/fef1xqdt/5/

<svg width=500 height=500>
<g  class="legend" transform="translate(50,30)" data-style-padding="10" style="font-size: 20px;"> 
<rect class="legend-box" x="-18" y="-28" height="152" width="175.828125"></rect>
<g>
<text y="0em" x="1em" >
<tspan dx="0" text-anchor="start">Austin</tspan><tspan dx="0" dy="20" text-anchor="start" style="font-size: 16px;">Detail Sublegend</tspan></text>
<text y="2em" x="1em">New York</text>
<text y="4em" x="1em">San Francisco</text>
<circle cy="-0.25em" cx="0" r="0.4em" style="fill: rgb(44, 160, 44);"></circle>
<circle cy="1.75em" cx="0" r="0.4em" style="fill: rgb(31, 119, 180);"></circle>
<circle cy="3.75em" cx="0" r="0.4em" style="fill: rgb(255, 127, 14);"></circle></g>
</g>
</svg>

I read that whitespace between tspans messes things up...I don't have any. I would really like to understand why putting dx="0" for both tspans doesn't work.


Solution

  • Just set them to have the same x position if that's what you want. The different font size means it doesn't look quite right though. Maybe you could add some additional delta bodge factor to cope with that.

    .legend rect {
      fill:white;
      stroke:black;
      opacity:0.8;}
    <svg width=500 height=500>
    <g  class="legend" transform="translate(50,30)" data-style-padding="10" style="font-size: 20px;"> 
    <rect class="legend-box" x="-18" y="-28" height="152" width="175.828125"></rect>
    <g>
    <text y="0em" x="1em" >
      <tspan dx="0" text-anchor="start">Austin</tspan><tspan x="1em" dy="20" text-anchor="start" style="font-size: 16px;">Detail Sublegend</tspan></text>
    <text y="2em" x="1em">New York</text>
    <text y="4em" x="1em">San Francisco</text>
    <circle cy="-0.25em" cx="0" r="0.4em" style="fill: rgb(44, 160, 44);"></circle>
    <circle cy="1.75em" cx="0" r="0.4em" style="fill: rgb(31, 119, 180);"></circle>
    <circle cy="3.75em" cx="0" r="0.4em" style="fill: rgb(255, 127, 14);"></circle></g>
    </g>
    </svg>