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.
from CSS-Tricks https://ift.tt/CySkE94
via IFTTT
No comments:
Post a Comment