How to Create Text in SVG: Simple Syntax and Example
To create text in SVG, use the
<text> element inside an <svg> container. Set the position with x and y attributes and place your text content between the tags.Syntax
The <text> element is used to add text inside an SVG. You specify the position using the x and y attributes, which set the starting point of the text. The text content goes between the opening and closing <text> tags.
- <svg>: The container for SVG graphics.
- <text>: The element that holds the text.
- x: Horizontal position of the text start.
- y: Vertical position of the text baseline.
html
<svg width="200" height="100" xmlns="http://www.w3.org/2000/svg"> <text x="10" y="50">Your text here</text> </svg>
Output
A 200x100 box with the text 'Your text here' starting near the left and vertically centered around 50px.
Example
This example shows how to create a simple SVG with the text "Hello, SVG!" positioned at coordinates (20, 40). The text is black by default.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>SVG Text Example</title> </head> <body> <svg width="300" height="100" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Example of SVG text"> <text x="20" y="40" font-family="Arial" font-size="24" fill="black">Hello, SVG!</text> </svg> </body> </html>
Output
A 300x100 white area with the black text 'Hello, SVG!' near the top-left corner at position (20,40).
Common Pitfalls
Common mistakes when creating text in SVG include:
- Forgetting to set
xandyattributes, which can cause the text to not appear where expected. - Not including the
xmlnsattribute on the<svg>element, which can cause rendering issues in some browsers. - Using CSS properties that SVG does not support directly on
<text>(liketext-align), instead use SVG-specific attributes liketext-anchor.
Example of wrong and right usage:
html
<svg width="200" height="50" xmlns="http://www.w3.org/2000/svg"> <!-- Wrong: no x and y, text may not show as expected --> <text fill="red">Missing position</text> <!-- Right: with x and y set --> <text x="10" y="30" fill="green">Positioned text</text> </svg>
Output
Red text may appear at default position (usually 0,0); green text appears clearly at (10,30).
Quick Reference
Tips for working with SVG text:
- Always set
xandyto position text. - Use
font-family,font-size, andfillto style text. - Use
text-anchorto align text horizontally (start, middle, end). - Remember SVG text baseline is at
y, so vertical alignment may need adjustment. - Include
xmlns="http://www.w3.org/2000/svg"in the<svg>tag for proper rendering.
Key Takeaways
Use the element inside
Style SVG text with font-family, font-size, fill, and text-anchor attributes.
Always include the xmlns attribute on the
Remember the y attribute sets the baseline, so vertical alignment may need tweaking.
Avoid CSS text-align; use SVG's text-anchor for horizontal alignment.