xmltextsvgword-wrap

Auto line-wrapping in SVG text


I would like to display a <text> in SVG what would auto-line-wrap to the container <rect> the same way as HTML text fills <div> elements. Is there a way to do it? I don't want to position lines separately by using <tspan>s.


Solution

  • Text wrapping is not part of SVG1.1, the currently implemented spec.

    In case you are going to use your SVG graphic on the Web, you can embed HTML inside SVG via the <foreignObject/> element. Example:

    <svg ...>
    
    <switch>
    <foreignObject x="20" y="90" width="150" height="200">
    <p xmlns="http://www.w3.org/1999/xhtml">Text goes here</p>
    </foreignObject>
    
    <text x="20" y="20">Your SVG viewer cannot display html.</text>
    </switch>
    
    </svg>
    

    If you are targeting a pure SVG renderer without HTML support or want your graphic to be editable using professional vector graphics manipulation software (Adobe Illustrator, Inkscape, ...), this solution will probably not suit you.