Understanding SVG text-anchor Alignment

The text-anchor property in Scalable Vector Graphics (SVG) defines how a text string is aligned horizontally relative to its defined coordinate point (x, y). This article explains the mechanics of the text-anchor property, detailing how its three primary values—start, middle, and end—position text along its baseline, and how text direction affects this behavior.

The Anchor Point Concept

In SVG, text is rendered using the <text> element, which requires x and y attributes to establish an anchor coordinate:

<text x="100" y="50" text-anchor="value">Sample Text</text>

The text-anchor property dictates where the text string sits in relation to this exact (x, y) point.

The Three text-anchor Values

1. start (Default)

When text-anchor is set to start, the start of the text string is placed at the given x coordinate.

<!-- Text begins at x=100 and extends to the right -->
<text x="100" y="50" text-anchor="start">Left-aligned text</text>

2. middle

When text-anchor is set to middle, the geometric center of the rendered text string is aligned directly over the x coordinate.

<!-- Text center is positioned exactly at x=100 -->
<text x="100" y="50" text-anchor="middle">Centered text</text>

3. end

When text-anchor is set to end, the end of the text string is aligned with the x coordinate.

<!-- Text ends at x=100 and extends to the left -->
<text x="100" y="50" text-anchor="end">Right-aligned text</text>

Interaction with Text Direction (direction Property)

The terms start and end are logical rather than physical directions. Their visual behavior depends on the SVG direction property (or the CSS direction rule):

Usage in CSS

The text-anchor property can be declared as an SVG presentation attribute or within a CSS stylesheet:

.chart-label-left {
  text-anchor: start;
}

.chart-label-center {
  text-anchor: middle;
}

.chart-label-right {
  text-anchor: end;
}

By leveraging text-anchor, SVG text can be aligned cleanly without manually calculating text widths or bounding boxes.