How to Use SVG stroke-dasharray for Dashed Lines

The stroke-dasharray property in SVG is an essential presentation attribute and CSS property used to transform solid outlines into dashed or dotted patterns. This article explains the core purpose of stroke-dasharray, how its numeric values determine alternating dash and gap lengths, how the browser handles odd and even value lists, and how developers leverage it for both static styling and dynamic SVG path animations.

The Purpose of stroke-dasharray

By default, SVG vector shapes such as paths, circles, rectangles, and lines render with continuous, solid strokes. The primary purpose of the stroke-dasharray property is to break this solid line into a sequence of visible dashes and invisible gaps. It provides complete control over the rhythm, spacing, and proportion of dashed strokes across any SVG graphic.

How stroke-dasharray Works

The value of stroke-dasharray consists of a list of comma- or space-separated numbers that specify the lengths of alternating dashes and gaps.

Key Practical Applications

  1. Data Visualization: In charts and graphs, stroke-dasharray helps distinguish between different data sets, secondary trends, or projected targets on a shared coordinate grid.
  2. Dotted Lines and Borders: When paired with stroke-linecap="round", small dash lengths combined with larger gap lengths create perfectly rounded dots along complex vector curves.
  3. SVG Line Drawing Animations: A prominent modern use case involves pairing stroke-dasharray with stroke-dashoffset. By setting the dash array length equal to or greater than the total path length, developers can shift the offset with CSS keyframes or JavaScript to create the illusion of a line drawing itself onto the screen.