O'Reilly logo

SVG Essentials by J. David Eisenberg

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

The tspan element

Another consequence of not knowing a text string’s length in advance is that it is difficult to construct a string with varying text attributes, such as this sentence, which switches among italic, normal, and bold text. If you had only the <text> element, you’d need to experiment to find where each differently styled segment of text ended in order to space them properly. To solve this problem, SVG provides the <tspan>, or text span element. Analogous to the XHTML <span> element, <tspan> is a tabula rasa that may be embedded in text content, and upon which you may impose style changes. The <tspan> remembers the text position, so you don’t have to. Thus, Example 8-4, which produces the display in Figure 8-6.

Example 8-4. Using tspan to change styles

<text x="10" y="30" style="font-size:12pt;">
    Switch among
    <tspan style="font-style:italic">italic</tspan>, normal,
    and <tspan style="font-weight:bold">bold</tspan> text.
</text>
Styles changed with tspan

Figure 8-6. Styles changed with tspan

In addition to changing presentation properties such as font size, color, weight, etc., you can also use attributes with <tspan> to change the positioning of individual letters or sets of letters. If, for example, you want superscripts or subscripts, you can use the dy attribute to offset characters within a span. The value you assign to this attribute is added to the vertical position of the characters, and ...

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