SVG Text

SVG has its own element for rendering text. Unlike HTML text, SVG text is positioned precisely using coordinates, giving you pixel-perfect control over where and how text appears inside your graphic.

The text Element

The text element renders text at a specific position. Its core attributes are:

SVG text inherits standard font-related CSS properties and presentation attributes, including font-family, font-size, font-weight, font-style, and fill (to set the text color).

The tspan Element

SVG does not automatically wrap text onto new lines. To create multi-line text or to style individual words within a text block differently, you nest tspan elements inside your text element.

The dy attribute on a tspan can be quite handy. It moves the text by a relative amount from the last baseline, making it easy to simulate line spacing.

Example of SVG Text

View Output

Text Alignment with text-anchor

By default, the x and y position of a text element anchors the start of the text. You can change this with the text-anchor property:

Value Effect
start Default. The start of the text is at x,y.
middle The center of the text is at x,y. Useful for centering text horizontally.
end The end of the text is at x,y.

To perfectly center text inside an SVG, set x to half the SVG width, text-anchor="middle", and a y value that accounts for the baseline.