Say you might have a line in SVG:
<svg>
<line x1="0" y1="30" x2="500" y2="30" stroke-color="#f8a100" />
</svg>
You should utilize the stroke-dasharray
property in CSS to make dashes:
line {
stroke-dasharray: 5;
}
That 5
worth is a relative unit based mostly on the scale of the SVG’s viewBox
. We may use any CSS size, actually. However what it does is make a sample of dashes which might be 5 models lengthy with 5 unit gaps between them.
Up to now, so good. We will use two values the place the second worth individually units the hole size:
Now now we have dashes which might be 5 models and gaps which might be 10. Let’s strive a 3rd worth:
See how we’re forming a sample right here? It goes:
- Sprint: 5 models
- Hole: 10 models
- Sprint: 15 models
You’d suppose it repeats after that in the very same cadence. However no! It if did, we’d have dashes bumping into each other:
- Sprint: 5 models
- Hole: 10 models
- Sprint: 15 models
- Sprint: 5 models
- Hole: 10 models
- Sprint: 15 models
- …and so forth.
As a substitute, stroke-dasharray
will get all sensible and duplicates the sample if there are an odd variety of values So…
stroke-dasharray: 5 10 15;
/* is similar as */
stroke-dasharray: 5 10 15 5 10 15;
That’s really why a single worth works! Earlier, we declared a single 5
worth. That’s actually the identical as saying stroke-dasharray: 5 5
. With out the second worth, stroke-dasharray
implicitly duplicates the primary worth to get a repeatable sample. In any other case, it’d simply be a strong line of dashes which might be 5 models lengthy, however no gaps between them!
The sample additionally is determined by the scale of the form itself. Our SVG line
is 500 models. Let’s set bigger stroke-dasharray
values and add them up:
stroke-dasharray: 10 20 30 40 50; /* 150 models */
If the sample runs 4 instances (150 models ⨉ 4 iterations), we’re coping with 600 complete models. That extra 100 models is lopped off to forestall the sample from overflowing itself.
That’s all.
🎩 Hat tip to Joshua Dance for calling this out!