Chapter 34: SVG in HTML

SVG Typography

Vector typesetting with `<text>`, `<tspan>`, alignment matrices (`text-anchor`, `dominant-baseline`), and curvilinear paths (`<textPath>`).

LEARNING OBJECTIVES
  • Understand why SVG text has no default HTML box-model line wrapping and requires vector baseline anchoring.
  • Master horizontal alignment via text-anchor (start, middle, end) and vertical alignment via dominant-baseline (alphabetic, middle, hanging).
  • Structure multi-line and multi-styled text blocks using <tspan> and coordinate offsets (dx, dy).
  • Wrap and typeset text along arbitrary curves and circles using <textPath>.
🎬 INTERACTIVE VISUAL PIPELINE Core Architecture Simulation
🌐
1. Input
Directives & Tags
⚙️
2. Parse
Tokenizer & AST
🌳
3. Layout
Box Model & Flow
🎨
4. Render
GPU Paint & Composite
PHASE 1: INPUT & DIRECTIVES
Browser receives declarative markup stream, parsing tag tokens and initializing component state.

📖 The Mental Model & Story (Intuitive Foundation)

Imagine the difference between two printing methods:

  1. The Modern Word Processor (HTML / CSS): Text is poured into rectangular boxes. When a sentence hits the right margin, it automatically word-wraps onto the next line, pushing all subsequent content downward.
  2. The Engraver's Caliper (SVG Typography): You place a metal stylus at an exact spatial coordinate $(X, Y)$ on a brass plaque. The text sits upon a mathematical baseline. It never automatically wraps; if your sentence is $1,000\text{px}$ long, it will march straight off the right edge of the plaque unless you manually calibrate its path or anchor point.
SVG TYPOGRAPHIC BASELINE GRID:
                       [Ascender]   ----------------- (Top of capital letters)
                           H        ----------------- [Hanging Baseline]
     dominant-baseline ->  e        ----------------- [Middle Baseline]
                           l        
  (X, Y) Coordinate ---->  p y      ----------------- [Alphabetic Baseline (Default)]
                           |        ----------------- [Descender]
                           
     |<-- start              middle                end -->|
                      (text-anchor alignment)

Because SVG text is declared as true vector typography rather than flattened raster pixels, it remains $100%$ selectable, copy-pasteable, searchable (via Ctrl+F), and readable by assistive screen readers.


Technical Deep Dive & Specifications

1. The <text> Element & Coordinate Anchoring

<text x="100" y="50" fill="#ffffff" font-size="20" font-family="sans-serif">
  Vector Typography
</text>

By default, the $(x, y)$ coordinate specifies where the leftmost point of the alphabetic baseline sits. This means text appears above the $Y$ coordinate, not below it!


2. Horizontal Alignment: text-anchor

The text-anchor property determines how text horizontally aligns relative to the anchor point $X$:

Value Alignment Behavior
start (default) The start of the text string is aligned to $X$ (text flows to the right).
middle The geometric center of the text string is aligned to $X$.
end The end of the text string is aligned to $X$ (text flows to the left).
text-anchor="start":    (X,Y) [ HELLO WORLD ] --->
text-anchor="middle":   <--- [ HELLO ] (X,Y) [ WORLD ] --->
text-anchor="end":      <--- [ HELLO WORLD ] (X,Y)

3. Vertical Alignment: dominant-baseline

The dominant-baseline property aligns the text vertically relative to the anchor point $Y$:

Value Description Typical Use Case
auto / alphabetic (default) Bottom of standard Latin glyphs (excluding descenders like 'p', 'y', 'g'). Standard typography.
middle / central Mathematically centers the glyphs vertically over $Y$. Perfect for badge labels and buttons.
hanging Aligns top of capital letters to $Y$ (text hangs below $Y$). Top-aligned headers and Asian scripts.

The Golden Formula for Centering Text in SVG:

<text x="50%" y="50%" text-anchor="middle" dominant-baseline="central">
  Perfect Center
</text>

4. Multi-Line & Styled Spans with <tspan>

Because SVG text does not auto-wrap, multi-line typography is achieved using <tspan> with absolute x coordinates and relative dy (delta-y) line jumps:

<text x="50" y="50" font-size="16" fill="#f8fafc">
  Line 1 of typography
  <tspan x="50" dy="1.4em" fill="#38bdf8" font-weight="bold">Line 2 (Shifted down)</tspan>
  <tspan x="50" dy="1.4em" fill="#f43f5e">Line 3 (Shifted down)</tspan>
</text>

5. Curvilinear Typography: <textPath>

To wrap text along any organic Bézier curve or circle:

  1. Define a <path id="my-curve" d="..." /> inside a <defs> block.
  2. Nest a <textPath href="#my-curve"> inside a <text> element.
<defs>
  <path id="circle-track" d="M 50,100 A 50,50 0 1,1 150,100" fill="none" />
</defs>

<text fill="#f59e0b" font-size="14">
  <textPath href="#circle-track" startOffset="50%" text-anchor="middle">
    Text Flowing on a Curve
  </textPath>
</text>

SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
HTML STARSHIP CODE TERMINAL example.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45°C
INSPECTING DOM: VALID
TAGS: SCANNING...

💻 Interactive Code Playground

Starter Code

Line-by-Line Code Breakdown

  • Line 56: <path id="arch-top" d="M 70,160 A 80,80 0 0,1 230,160" fill="none"/> defines an invisible upper circular arch inside <defs>.
  • Line 68–72: <textPath href="#arch-top" startOffset="50%" text-anchor="middle"> attaches text to #arch-top. startOffset="50%" and text-anchor="middle" mathematically center the text at the apex of the arch.
  • Line 75: <text x="150" y="150" text-anchor="middle" dominant-baseline="central"> uses the golden centering formula to place "SVG 2026" dead center inside the inner circle.
  • Line 81–87: Demonstrates multi-line code formatting using <tspan x="0" dy="1.5em"> to manually calculate line jumps in SVG coordinate space.

Expected Browser Render Output


SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
HTML STARSHIP CODE TERMINAL playground.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45°C
INSPECTING DOM: VALID
TAGS: SCANNING...
+---------------------------------------------------------------+
|  SVG Precision Typography & Curvilinear Text                  |
|                                                               |
|        . - HTML MASTERCLASS - .       const vectorText = {    |
|      /                          \        anchor: 'middle',    |
|     |         SVG 2026           |       baseline: 'central'  |
|      \                          /     };                      |
|        ' - - - - - - - - - - - '      ~ Organic Path Flow ~   |
+---------------------------------------------------------------+

🏋️ Hands-On Exercise

🎯 The Challenge: Design a Verified Certified Seal Stamp

Objective: Design an official circular corporate stamp with two curved text labels:

  1. Top Arc: "VERIFIED FRONTEND ARCHITECT"
  2. Bottom Arc: "OFFICIAL CERTIFICATION"
  3. Center Emblem: A central 5-point star or checkmark with the issue year.

Instructions:

  1. Create an SVG with viewBox="0 0 200 200".
  2. Define a top arc path #seal-top in <defs> curving over the top half of a $75\text{px}$ radius circle.
  3. Define a bottom arc path #seal-bottom in <defs> curving over the bottom half. (Take note of path direction so bottom text is not rendered upside down!).
  4. Bind text to both arcs using <textPath>.
  5. Center the label "2026" with text-anchor="middle" and dominant-baseline="central" inside the stamp.

🏁 Starter Code Sandbox

SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
STARTER CODE SANDBOX exercise.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45°C
INSPECTING DOM: VALID
TAGS: SCANNING...

⚠️ Common Pitfalls

  1. Expecting Word Wrap Without <tspan>: Long strings in SVG do not wrap automatically. If you write 50 words inside a <text> tag, they will extend infinitely along a single horizontal line across your screen.
  2. Upside-Down <textPath> Curves: The direction of text flow is determined strictly by the start and end direction of the referenced <path>. If text is rendering upside down along the bottom of a circle, reverse the direction of your path coordinates!
  3. The y Coordinate Clipping Gotcha: Placing <text x="0" y="0">Title</text> causes the text to appear invisible because text is rendered above the baseline $Y=0$, clipping it off the top edge of the SVG viewport. Set $Y$ equal to at least the font-size.

💡 Pro Tips

  1. Disabling Accidental Selection on Icons: For UI buttons where SVG icons contain text labels, apply user-select: none; pointer-events: none; via CSS to prevent double-click text selection highlights when users click rapidly.
  2. Sub-Pixel Crispness via text-rendering: Use text-rendering: geometricPrecision; in CSS on SVG text elements to optimize vector letterform anti-aliasing during dynamic animations.

📌 Key Takeaways

  • Vector Text: SVG <text> elements contain real, searchable, accessible DOM characters positioned along vector coordinates.
  • text-anchor: Manages horizontal alignment (start, middle, end) relative to coordinate $X$.
  • dominant-baseline: Manages vertical baseline alignment (alphabetic, middle/central, hanging) relative to coordinate $Y$.
  • <tspan>: Provides multi-line formatting and inline coordinate jumps (dx, dy).
  • <textPath>: Binds text along arbitrary <path> shapes for circular stamps, banners, and organic typography.
  • --
⭐ LEARN: HTML 🌟 ⚔️ QUIZ BATTLE ARENA // ACTIVE
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 1 / 3

Why does <text x="50" y="0">Hello World</text> appear cut off at the top of an SVG?

Question 1 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 2 / 3

Which combination of attributes guarantees that an SVG text string will be mathematically centered horizontally and vertically inside a coordinate point $(X, Y)$?

Question 2 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 3 / 3

How do you wrap text along a circular path in SVG?

Question 3 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP