O'Reilly logo

SVG Text Layout by Kurt Cagle, Amelia Bellamy-Royds

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required