How to make the svg with a single <path>
tag making a horizontal line fill up the entire width of the parent container of the svg.
https://codesandbox.io/s/charming-goldstine-wh7td4?file=/src/index.tsx
.container {
width: 400px;
height: 100px;
background: rgba(0, 0, 255, 0.2);
position: relative;
}
svg {
width: 100%;
height: 100%;
stroke: black;
stroke-width: 20px;
position: absolute;
bottom: 0;
left: 0;
right: 0;
}
svg path {
width: 100%;
height: 100%;
}
<h4>
Line should fill 100% width of the container of the svg. (the svg should be absolute
positioned)
</h4>
<div class="container">
<svg viewBox="0 0 1000 1" xmlns="http://www.w3.org/2000/svg">
<path
d="M 0,0 H 100%"
// d="M 0, 5 L 100, 5"
/>
</svg>
</div>
2
Answers
You can set it to 100% by modifying
d="M 0,0 H 100%"
.For example, here I want to be 90% so I use:
d="M 0,0 H 900%"
p.s: the percentage is relevant to with of the
viewbox
which is the third parameter:viewBox="0 0 1000 1"
As commented by enxaneta:
<path>
elements can’t use percentage valuesunlike primitives like
<line>
,<rect>
,<circle>
,<ellipse>
.See "9.3.2. Specifying path data: the ādā property"
So the obvious solution would be to use a
<line>
element instead.You might also use
<line>
elements for fluid layout width – omitting the<viewBox>
(See 2nd example)If you really need to use
<path>
you might also applypreserveAspectRatio="none"
andvector-effect="non-scaling-stroke"
to get a similar behavior. (3rd example=