Chapter 6. Casting Anchor

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 text-align property.

Start, Middle, or End

SVG text alignment is controlled by the text-anchor property. The point you specify with x and y is the anchor point for that span of text, and text-anchor controls whether this point is positioned at the start, middle, or end of the span.

The default for text-anchor is start. Other values (end or middle) can be specified as a presentation attribute or via CSS.

Tip

The 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.

Get SVG Text Layout now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.