Text in SVG (Font, Anchor, Alignment)
This page deals with the typography attributes of text. The text tags are described on the linked page. SVG supports many of the more esoteric aspects of typography. While all the attributes have their uses, this tutorial only looks at the more commonly used and supported attributes. The full list in the Text and Font Reference.
Since the W3C is responsible for HTML, CSS and SVG, it is perhaps not surprising the level of sharing going on here. So, if you have done font styling in HTML some of the following attributes will look familiar. The same external stylesheet could be used to style text for a SVG document and an HTML page. While optional, any decent SVG viewer will have CSS support as well.
Font Styling
The basic font attributes are quite similar in SVG and HTML. The wide support for CSS by SVG viewers makes this pretty convenient.
Attribute | Values | Initial | Comments |
font-family | CSS font family | Depends | Name of font or font family. See CSS2 Specification |
font-size | (pt, px, em, %, etc | inherit) | medium | The font size. Any SVG unit can be used. |
font-style | (normal | italic | oblique | inherit) | normal | Style in which letters are rendered. |
font-variant | (normal | small-caps | inherit) | normal | 'small-caps' makes all lower case letters render as small capitals. |
font-weight | (normal | bold | inherit | +others) | normal | The thickness of the font. |
Commonly used values for font-family:
- Arial, Helvetica, sans-serif
- Tahoma, Geneva, sans-serif
- 'Times New Roman', serif
Anchors and Alignment
The anchor point is the x and y position defined by the text tag. The baseline is the line where text naturally sits. Some characters like 'y' in English drop under the baseline. The default placement of text is with the baseline touching the anchor point and to the right of the anchoring point.
The many options for the attribute alignment-baseline alter the positioning of the baseline with respect to the anchor point. The attribute text-anchor changes where the bounding box for the text is placed with respect to the anchor point.
Combining 'middle' for both options is convenient for positioning text centered upon a spot regardless of size and length.
<text x="80" y="30" font-size="20" text-anchor="middle" alignment-baseline="middle"> Pretty in the middle! </text>
CSS/Attributes
To style text using presentation attributes, use XML's attribute format (attribute="value"). To style using css, just add the same attribute as a style.
<text font-size="30">...</text> <text style="font-size:30;">...</text>