It is possible to scale an SVG while keeping its height
and/or stroke-width
to a fixed value? I am looking for a way to keep the nice linecap
rounded and scaled to the defined height (10px, or stroke-width: 10px
)
Sandbox of what I'm trying to do: https://codesandbox.io/s/scale-svg-with-fixed-stroke-width-snrh6r
But unsure how to get that to work or if is even possible...
CodePudding user response:
Linecaps will expand the width of your <path>
.
Try this:
- set
width:100%
andheight:10px
for svg preserveAspectRatio="none"
will squeeze the svg/path to the total width of the parent divvector-effect: non-scaling-stroke
ensures line caps won't be distorted- the
<path>
is drawn across the entire width overflow:visible
prevents the line caps from being cut offpadding:0 5px 0 5px
adjusts the svg viewport by a left and right 5px offset on both sides
.App {
font-family: sans-serif;
text-align: center;
resize: horizontal;
overflow: auto;
width: 352px;
padding: 0.3em;
border: 1px solid #ccc;
}
.stackbar-svg {
overflow: visible;
box-sizing: border-box;
padding: 0 5px 0 5px;
}
path {
stroke: red;
fill: red;
stroke-width: 10px;
stroke-linecap: round;
vector-effect: non-scaling-stroke;
}
<div style="width: 238px;">
<svg width="100%" height="10" viewBox="0 0 100 10" preserveAspectRatio="none">
<path id="stackbar-path-0" d="M 0 5 L 100 5" />
</svg>
<p>As you resize the div, the stroke-width shrink<br>How to keep it at a fixed 10px?</p>
</div>
You could make the <path>
element a 100% width and control