Categories: css-tricks.com

How stroke-dasharray Patterns Work

Say you have a line in SVG:

<svg>
  <line x1="0" y1="30" x2="500" y2="30" stroke-color="#f8a100" />
</svg>

You can use the stroke-dasharray property in CSS to make dashes:

line {
  stroke-dasharray: 5;
}

That 5 value is a relative unit based on the size of the SVG’s viewBox. We could use any CSS length, really. But what it does is make a pattern of dashes that are 5 units long with 5 unit gaps between them.

So far, so good. We can use two values where the second value individually sets the gap length:

Now we have dashes that are 5 units and gaps that are 10. Let’s try a third value:

See how we’re forming a pattern here? It goes:

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

You’d think it repeats after that in the exact same cadence. But no! It if did, we’d have dashes bumping into one another:

  • Dash: 5 units
  • Gap: 10 units
  • Dash: 15 units
  • Dash: 5 units
  • Gap: 10 units
  • Dash: 15 units
  • …and so on.

Instead, stroke-dasharray gets all smart and duplicates the pattern if there are an odd number of values So…

stroke-dasharray: 5 10 15;

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

That’s actually why a single value works! Earlier, we declared a single 5 value. That’s really the same as saying stroke-dasharray: 5 5. Without the second value, stroke-dasharray implicitly duplicates the first value to get a repeatable pattern. Otherwise, it’d just be a solid line of dashes that are 5 units long, but no gaps between them!

The pattern also depends on the size of the shape itself. Our SVG line is 500 units. Let’s set larger stroke-dasharray values and add them up:

stroke-dasharray: 10 20 30 40 50; /* 150 units */

If the pattern runs four times (150 units ⨉ 4 iterations), we’re dealing with 600 total units. That additional 100 units is lopped off to prevent the pattern from overflowing itself.

That’s all.

🎩 Hat tip to Joshua Dance for calling this out!


How stroke-dasharray Patterns Work originally published on CSS-Tricks. You should get the newsletter.

hnikoloski

Share
Published by
hnikoloski

Recent Posts

Demystifying Screen Readers: Accessible Forms & Best Practices

This is the 3rd post in a small series we are doing on form accessibility.…

2 weeks ago

Managing User Focus with :focus-visible

This is going to be the 2nd post in a small series we are doing…

4 weeks ago

The Power of :has() in CSS

Hey all you wonderful developers out there! In this post we are going to explore…

1 month ago

Accessible Forms with Pseudo Classes

Hey all you wonderful developers out there! In this post, I am going to take…

1 month ago

Passkeys: What the Heck and Why?

These things called passkeys sure are making the rounds these days. They were a main attraction at W3C…

1 year ago

Some Cross-Browser DevTools Features You Might Not Know

I spend a lot of time in DevTools, and I’m sure you do too. Sometimes…

1 year ago