How to Align Text to an SVG Path with textPath

Aligning text along an arbitrary path in SVG is achieved using the <textPath> element inside a standard <text> element. This guide explains how to define a reusable vector path, attach text to follow that geometry, and control alignment, offsets, and orientation for precise visual layouts.

The Basic Structure

To render text along a custom vector path, you must define the path with a unique id attribute, then reference that path within a <textPath> element.

<svg viewBox="0 0 500 200" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <!-- 1. Define the arbitrary path -->
    <path id="curvePath" d="M 50 150 Q 250 20 450 150" fill="none" stroke="lightgray" />
  </defs>

  <!-- Optional: Render the path visually -->
  <use href="#curvePath" />

  <!-- 2. Reference the path inside textPath -->
  <text font-family="sans-serif" font-size="20" fill="black">
    <textPath href="#curvePath">
      This text flows along an arbitrary curved path.
    </textPath>
  </text>
</svg>

Controlling Alignment and Position

Several attributes dictate how text aligns and distributes across the path:

1. The startOffset Attribute

The startOffset attribute specifies the distance from the beginning of the path where the text starts. It accepts absolute units (such as pixels) or percentages.

2. The text-anchor Attribute

The text-anchor CSS property determines the alignment point of the text relative to the startOffset.

3. The side Attribute

The side attribute determines which side of the path the text is rendered on.

4. The method and spacing Attributes

Centering Text Example

<svg viewBox="0 0 600 300" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <path id="wave" d="M 50 150 C 150 50, 250 250, 350 150 S 550 50, 550 150" fill="none" />
  </defs>

  <text font-size="18" fill="#0055ff">
    <textPath href="#wave" startOffset="50%" text-anchor="middle">
      Centered text along a cubic Bézier wave.
    </textPath>
  </text>
</svg>

Key Considerations

  1. Path Direction: Text flows strictly in the direction the path was drawn (from its start point M to its termination point). If text appears upside down, reverse the order of path commands or use side="right".
  2. Path Length and Truncation: If the rendered text is longer than the path length, any text extending beyond the path endpoint is clipped and will not be displayed.
  3. Namespace Compatibility: Modern browsers use href="#pathId". For legacy browser support, include xlink:href="#pathId" alongside the standard href.