The textLength attribute, available on SVG <text> and <tspan> elements, lets you specify the width of the space into which the text will draw. The user agent will ensure that the text does not extend farther than that distance, using the method or methods specified by the lengthAdjust attribute. By default, only the spacing between characters is adjusted, but the glyph size can also be adjusted if you change lengthAdjust.
By using textLength, you can ensure that your SVG text displays at the same width regardless of conditions including web fonts failing to load (or not having loaded yet).
You can use this attribute with the following SVG elements:
<svgviewBox="0 0 200 60"xmlns="http://www.w3.org/2000/svg"><texty="20"textLength="6em">Small text length</text><texty="40"textLength="120%">Big text length</text></svg>
First, a <rect> element is used to create and stroke a rectangle to contain the text. Then <text> is used to create the text element itself, with an id of "hello".
HTML
The HTML is also simple, with only two displayed elements contained inside a grouping <div>:
The <input> element, of type "range", is used to create the slider control the user will manipulate to change the width of the text. A <span> element of ID "widthDisplay" is provided to display the current width value.
JavaScript
Finally, let's have a look at the JavaScript code. It starts by stashing references to the elements it will need to access, using Document.getElementById():
After fetching the element references, an EventListener is established by calling addEventListener() on the slider control, to receive any input events which occur. These events will be sent any time the slider's value changes, even if the user hasn't stopped moving it, so we can responsively adjust the text width.
When an "input" event occurs, we call newValueSpecifiedUnits() to set the value of textLength to the slider's new value, using the SVGLength interface's SVG_LENGTHTYPE_PX unit type to indicate that the value represents pixels. Note that we have to dive into textLength to get its baseVal property; textLength is stored as an SVGLength object, so we can't treat it like a plain number.
After updating the text width, the contents of the widthDisplay box are updated with the new value as well, and we're finished.
Result
Here's what the example looks like. Try dragging the slider around to get a feel for what it does.