liveBook · Manning

Tspan element

As explained in D3.js in Action, Third Edition

A tspan element is an SVG text subelement that allows a portion of text to have independently positioned or styled content.

A tspan element is an SVG text subelement for positioning or styling part of a text label independently. SVG text does not automatically reflow like HTML, so separate tspans provide explicit control over multiline labels. section 5.2.3

Position and format each span with these attributes:

  • Use x and y to place a text baseline relative to the SVG container. section 5.2.3
  • Use dx and dy to shift a span relative to the preceding text or tspan element. section 5.2.3
  • Remember that text-anchor controls horizontal baseline behavior and dominant-baseline controls vertical baseline behavior. section 5.2.3
  • Combine tspan elements with opacity and font-size styling when individual lines need different visual emphasis. section 5.2.3

Multiline streamgraph axis label

const label = svg.append("text").attr("dominant-baseline", "hanging"); label.append("tspan").text("Total revenue"); label.append("tspan").text("(million USD)").attr("dx", 5); label.append("tspan").text("Adjusted for inflation").attr("x", 0).attr("dy", 20).attr("fill-opacity", 0.7).style("font-size", "14px"); The first two lines stay close together, while the third returns to x = 0 and moves downward by 20 units. section 5.2.3

Figure 5.17 tspan elements allow for manipulating the style and position of subtext items separately. We use the attributes dx and dy to set a position relative to the previous text element.
figure

Inspect how dx and dy position subtext relative to the preceding text element. section 5.2.3

How D3.js in Action, Third Edition covers it

How deep it goes
Explains baseline-relative attributes and demonstrates incremental positioning and styling, stopping short of broader SVG text layout.
Examples
Uses a three-line streamgraph axis label for total revenue, units, and inflation adjustment.
What it assumes
Assumes basic SVG text and D3 append and attr methods while teaching baseline positioning from the example.
What you can do after
Build multiline SVG labels with independently positioned and styled text spans.
How it connects
Connects tspan elements to SVG text, text-anchor, dominant-baseline, and D3 selection methods.

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.