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.
- Even Number of Values: When you specify an even
number of values (such as
stroke-dasharray="10, 5"), the first value defines the dash length (10 units), and the second defines the gap length (5 units). This sequence repeats continuously along the entire length of the path. - Single Value: Providing a single number (such as
stroke-dasharray="8") is shorthand for equal dashes and gaps. The browser automatically repeats the value, resulting in an 8-unit dash followed by an 8-unit gap. - Odd Number of Values: If you provide an odd list of
numbers (such as
stroke-dasharray="5, 10, 15"), the SVG renderer duplicates the pattern to create an even number of items (5, 10, 15, 5, 10, 15). This ensures the alternating dash-gap sequence remains consistent without inversion.
Key Practical Applications
- Data Visualization: In charts and graphs,
stroke-dasharrayhelps distinguish between different data sets, secondary trends, or projected targets on a shared coordinate grid. - 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. - SVG Line Drawing Animations: A prominent modern use
case involves pairing
stroke-dasharraywithstroke-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.