SVG Text
SVG's <text> element draws real, selectable text directly on the canvas, positioned with coordinates and styled with font attributes instead of CSS box models.
The <text> Element
Unlike an <img> or a canvas drawing, SVG text is live text in the DOM: it can be selected, searched by the browser's find-in-page, indexed by search engines, and read by screen readers. The <text> element accepts any attribute a shape does, plus a handful of typography-specific ones, and its content is the literal string that gets rendered.
A Basic Text Label
<!DOCTYPE html>
<html>
<body>
<svg viewBox='0 0 200 80'>
<rect x='0' y='0' width='200' height='80' fill='#f4f4f8'/>
<text x='20' y='45' font-size='24' fill='#1f2937'>Hello, SVG!</text>
</svg>
</body>
</html>The x and y attributes set the anchor point for the first character's baseline, not its top-left corner the way CSS positioning would. dx and dy nudge the text by a relative offset, which is useful for fine-tuning a single line without recalculating absolute coordinates. When x or y is given a list of numbers, each value positions the corresponding character, letting you fan out or stagger individual letters.
Baseline, Offsets, and Per-Character Positioning
<!DOCTYPE html>
<html>
<body>
<svg viewBox='0 0 260 100'>
<line x1='10' y1='30' x2='250' y2='30' stroke='#cbd5e1' stroke-dasharray='4'/>
<text x='10' y='30' font-size='20' fill='#0f172a'>Baseline text</text>
<text x='10' y='60' dy='10' font-size='16' fill='#2563eb'>Nudged with dy</text>
<text x='10 26 42 58 74' y='90' font-size='18' fill='#16a34a'>Fan!</text>
</svg>
</body>
</html>Font Attributes and Fill
Because <text> is an SVG element, typography is set with presentation attributes (or CSS) rather than HTML tags: font-family, font-size, font-weight, font-style, and letter-spacing all work exactly as their CSS counterparts. Color comes from fill, not color -- a common trip-up for developers coming from HTML -- and an outline can be added with stroke.
- font-family accepts any stack, e.g. 'Georgia, serif'
- font-size accepts px, em, or unitless numbers (treated as px)
- font-weight is 'normal', 'bold', or a numeric value from 100-900
- fill sets the text color; stroke adds an outline around each glyph
- text-anchor sets 'start', 'middle', or 'end' alignment around x
Styled Multi-Attribute Text
<!DOCTYPE html>
<html>
<body>
<svg viewBox='0 0 260 100'>
<rect width='260' height='100' fill='#0f172a'/>
<text x='130' y='45' text-anchor='middle' font-family='Georgia, serif' font-size='26' font-weight='bold' fill='#fbbf24'>SVG Typography</text>
<text x='130' y='72' text-anchor='middle' font-size='14' fill='#e2e8f0' letter-spacing='2'>STYLED WITH ATTRIBUTES</text>
</svg>
</body>
</html>Exercise: SVG Text
Which element renders text in SVG?