Text in SVG (Font, Anchor, Alignment)

By mbystedt on Feb 28, 2014, 11:42:58 PM

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.

CSS font family
Name of font or font family. See CSS2 Specification
(pt, px, em, %, etc | inherit)
The font size. Any SVG unit can be used.
(normal | italic | oblique | inherit)
Style in which letters are rendered.
(normal | small-caps | inherit)
'small-caps' makes all lower case letters render as small capitals.
(normal | bold | inherit | +others)
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.

Example 1. The baseline is shown by the black lines and the x/y anchor position as an orange dot. (Download)

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!
Code 1. Text with text-anchor and alignment-baseline 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>
The two 'text' tags are equivalent.
Related Topics