如何将SVG大小精确调整以包裹其内容?

huangapple go评论47阅读模式
英文:

How to scale svg size to exactly wrap its content?

问题

我有一个非常简单的SVG,里面有一个圆:

<div>
  <svg className="main-svg">
    <circle pathLength="25" cx="50%" cy="50%" r="25%" />
  </svg>
</div>

然后,如果我对其进行样式化:

svg {
  height: 250px;
  width: 250px;
}

SVG 将占据 250px 的宽度和高度,但其中的圆将会小得多,因此圆周围会有不必要的空白空间。是否可以使SVG包装圆而不添加空白,以便定义SVG的宽度和高度将导致设置其中的圆的宽度和高度?

Stackblitz 链接:https://stackblitz.com/edit/react-ts-fwmjzn?file=style.css

英文:

I have a very simple svg with a circle inside:

&lt;div&gt;
  &lt;svg className=&quot;main-svg&quot;&gt;
    &lt;circle pathLength=&quot;25&quot; cx=&quot;50%&quot; cy=&quot;50%&quot; r=&quot;25%&quot; /&gt;
  &lt;/svg&gt;
&lt;/div&gt;

Then if I style it:

svg {
  height: 250px;
  width: 250px;
}

The svg will take up 250px width and height, but the circle inside it will be much smaller, so there's unwanted white space around the circle. Is it possible to make the svg wrap the circle without adding space, so that defining the width of height of the svg will result in setting the width and height of the circle inside it?

Stackblitz link: https://stackblitz.com/edit/react-ts-fwmjzn?file=style.css

答案1

得分: 2

将半径属性值设置为50%

<svg width="250" height="250" viewBox="0 0 250 250">
    <circle pathLength="25" cx="50%" cy="50%" r="50%" />
</svg>
英文:

Set radius attribute value to 50%

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-css -->

svg {border: 2px solid red; }

<!-- language: lang-html -->

&lt;svg width=&quot;250&quot; height=&quot;250&quot; viewBox=&quot;0 0 250 250&quot;&gt;
            &lt;circle pathLength=&quot;25&quot; cx=&quot;50%&quot; cy=&quot;50%&quot; r=&quot;50%&quot; /&gt;
        &lt;/svg&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月19日 23:08:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75501086.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定