How to Add Text to SVG Images
We can’t use regular HTML elements like paragraphs to add text within an SVG element. SVG has a dedicated text
element for that. We can position the text by setting the text’s bottom-left corner with the x
and y
attributes.
We can style it with the regular text formatting properties in CSS, except for coloring the text. We use the fill
and the stroke
attributes like in the case of any other shape in SVG. Here is an example of how to render text in SVG:
Text alignment
We can use the text-anchor
attribute to change the horizontal alignment of the text. By default, the text is anchored at the start of the text. We can change it to middle
to center the text or end
to anchor it at the end.
We can use the alignment-baseline
attribute to change the vertical alignment of the text. By default, the text is anchored at the baseline. We can change it to middle
to center the text or hanging
to anchor it at the top.
Paint order
There’s a new paint-order
attribute that defines if the shape should be filled or stroked first. The default value is fill stroke markers
, which means that the shape is filled first, then stroked, and then the markers are added.
You can change the order by setting the value to stroke fill markers
. This can result in a cool effect if we move the letters closer to each other by changing the letter-spacing
attribute.
How to draw text along a path
Drawing shapes is not the only use case for paths. In our primary example, we draw a quadratic Bézier curve and use it as the baseline for the text.
To bend the letters, we wrap the text in the textPath
element. We set the href
attribute to the id
of the path we want to use. The text will follow this path. Here, we also use the path as an underline, but the bending effect would also work if the path is invisible.