Reputation: 856
I am making an svg (a line element) and it's vertical. I want that svg line to scale according to the height of the container.
<div class="parent">
<svg viewBox="0 0 100 100">
<line x1="0" y1="0" x2="0" y2="20" style="stroke: black;stroke-width:1"/>
</svg>
</div>
Now if increase parent width the height of vertical line scales, but the requirement is, as we increase the height, length should increase proportionally.
Am i putting the viewBox
wrong?
Upvotes: 1
Views: 1261
Reputation: 206638
Scale SVG proportionally:
.parent {
background: yellow;
}
.parent svg {
height: 100%;
}
100px height
<div class="parent" style="height: 100px;">
<svg viewBox="0 0 2 100" preserveAspectRatio="none">
<line x1="0" y1="0" x2="0" y2="100" style="stroke: black; stroke-width:2"/>
</svg>
</div>
300px height
<div class="parent" style="height: 300px;">
<svg viewBox="0 0 2 100" preserveAspectRatio="none">
<line x1="0" y1="0" x2="0" y2="100" style="stroke: black; stroke-width:2"/>
</svg>
</div>
Scale SVG but keep stroke
.parent {
background: yellow;
}
.parent svg {
height: 100%;
}
100px height
<div class="parent" style="height: 100px;">
<svg viewBox="0 0 2 100" preserveAspectRatio="none">
<line x1="0" y1="0" x2="0" y2="100" style="stroke: black; stroke-width:2" vector-effect="non-scaling-stroke"/>
</svg>
</div>
300px height
<div class="parent" style="height: 300px;">
<svg viewBox="0 0 2 100" preserveAspectRatio="none">
<line x1="0" y1="0" x2="0" y2="100" style="stroke: black; stroke-width:2" vector-effect="non-scaling-stroke"/>
</svg>
</div>
Upvotes: 3
Reputation: 10235
I think you are looking for the vector-effect
attribute. If you set it to non-scaling-stroke
- this will enable you to keep the stroke of the line at 1 pixel independent of the size of the svg. Take a look at this example below, I've set up the svg to fill the parent:
.parent {
background: #efefef;
width: 200px;
height: 200px;
}
svg {
width: 100%;
height: 100%;
}
<div class="parent">
<svg viewBox="0 0 100 100">
<line x1="0" y1="0" x2="0" y2="100"
style="stroke: black;stroke-width:1"
vector-effect="non-scaling-stroke"/>
</svg>
</div>
Try changing the size of the parent around and you'll notice that the stroke width always remains consistent.
Upvotes: 2