Every modern word processor has the option to left-align, right-align, center, or justify text. CSS text layout uses the
text-align property to choose between these options for positioning text within the layout box.
For CSS or word processors, the page layout defines margins on either side of the text region. Alignment settings determine how extra whitespace is shifted within this space: accumulating on one side or the other, divided evenly on either side, or distributed in between words.
In SVG, there are no margins and no boxes. Each line of text is just as long as it needs to be. As we have seen, it might not even be a straight line. SVG does provide tools to center or right-align text. The options, however, are not as straightforward as the
SVG text alignment is controlled by the
text-anchor property. The point you specify with
y is the anchor point for that span of text, and
text-anchor controls whether this point is positioned at the
end of the span.
The default for
start. Other values (
middle) can be specified as a presentation attribute or via CSS.
text-anchor property is inherited, so it can be set once for the entire SVG if desired.
Example 6-1 displays three strings, with the same horizontal position but different
text-anchor values; Figure 6-1 shows the result. A vertical guideline marks the x position used to anchor all the text elements.