Search code examples
svgstroke-dasharray

SVG - stroke-dasharray with percentage units doesn't work as expected


I think I don't quite understand something here. Percentage units in stroke-dasharray are realtive to what? I was thinking relative to the SVG viewbox, but I was probably wrong.

My problem: I have an SVG with the width of 320px and the height of 160px. In this SVG I draw a line from x1 = "0%" to x2 = "100%", so it has a width of 320px just like the SVG.

Then I give the line: stroke-dasharray: 100% 100%;

For me it is surprising that the line is not drawn with the full width of the SVG, but only about 80%.

I think I don't quite understand something here. Pronounced units in stroke-dasharray are realtive to what? I was thinking relative to the SVG viewbox, but I was probably wrong.

My problem: I have an SVG with the width of 320px and the height of 160px. In this SVG I draw a line from x1 = "0%" to x2 = "100%", so it has a width of 320px just like the SVG.

Then I give the line: stroke-dasharray: 100% 100%;

For me it is surprising that the line is not drawn with the full width of the SVG, but only about 80%.

If someone has an idea, I would be happy to hear from you

Here the link to an example: https://codepen.io/stefka1210/pen/xxVwBom

html, body {
width: 100%;
height: 100%;
}
body {
display: flex;
align-items: center;
justify-content: center;
}
.container {
width: 320px;
height: 160px;
background: lightgrey;
}
svg {
width: 100%;
height: 100%;
}
line {
stroke-width: 2px;
}
#one {
stroke-dasharray: 100% 100%;
stroke: red;
}
#two {
stroke-dasharray: 320px 320px;
stroke: green;
}
<html>
<body>
    <div class="container">
    <svg x="0px" y="0px" viewBox="0 0 320 160" xmlns="http://www.w3.org/2000/svg">
        <g>
            <line id="one" x1="0%" y1="40%" x2="100%" y2="40%"></line>
            <line id="two" x1="0%" y1="60%" x2="100%" y2="60%"></line>
        </g>
    </svg>
</div>
</body>
</html>


Solution

  • Since a line can go in any direction, it would not make sense to link "percentage of the viewport" to either its width or height. Instead, 100% is set to the root mean square of width and height:

    \sqrt{\frac{width^{2}+height^{2}}{2}}

    For width = 320 and height = 160, that gives a length of 252.98.