SVG stroke-dasharray: The Pattern Behind the Dashes

Drawing a dashed line in SVG is straightforward with the CSS stroke-dasharray property. A single value, like 5, creates dashes that are 5 units long with 5-unit gaps. That unit is relative to the SVG’s viewBox.

Things get more interesting when you add more values. With two values, the second one sets the gap length independently — so stroke-dasharray: 5 10 gives 5-unit dashes and 10-unit gaps. Add a third value and the pattern extends: 5-unit dash, 10-unit gap, 15-unit dash.

You might expect that sequence to repeat as-is. It doesn’t. If it did, the pattern would look broken, with dashes colliding:

  • Dash: 5 units
  • Gap: 10 units
  • Dash: 15 units
  • Dash: 5 units
  • Gap: 10 units
  • Dash: 15 units

Instead, stroke-dasharray automatically duplicates the whole sequence when it contains an odd number of values. That’s why a single value like 5 really means 5 5 — the browser repeats the value to make the pattern repeatable. Without that duplication, you’d just get a long, 5-unit dash with no gap.

The math also depends on the shape’s total length. On a 500-unit line, setting larger values that add up to 150 units means the pattern fits four times, for 600 units total. That extra 100 units gets cut off so the pattern doesn’t overflow.

🎩 Hat tip to Joshua Dance for pointing out this quirk.

stroke-dasharray: 5 10 15;

/* is the same as */
stroke-dasharray: 5 10 15 5 10 15;