首页 > 解决方案 > SVG 文本,tspan 字体大小和居中

问题描述

我在 SVG 上遇到了字体大小问题,正如我们在 svg 中看到的, font-size:16px 与段落 font-size 不同,但它们具有相同的值16px。我想在段落中使用 svg 中的字体大小。

<tspan text-anchor="middle" class="tc-label-value">85</tspan>第二个问题,当我删除时 如何居中 <tspan class="label-text" text-anchor="middle" x="0" y="50" dy="15">Text in SVG</tspan> 我的意思是我有Text in svg和没有 的情况https://codepen.io/palaniichukdmytro/pen/BaaKbze

标签: htmlcsssvg

解决方案


svg 元素的字体大小应为 8.88 像素。为什么?因为 svg 的宽度是 100 个单位或 px ( viewBox="0 0 100 100" ) 并放大到 180px ( .wr{width: 180px;})。由于您需要 svg 中的字体大小看起来像 16px,因此实际字体大小应该是 16 * 100 / 180 = 8.88

.wr {
  width: 180px; 
}
.par{
  font-size: 16px;
}

svg{font-size: 8.88px;}
<div class='wr'>
  <svg viewBox="0 0 100 100" style="display: block;">
    <path d="M 95.5 50 A 45.5 45.5 0 1 1 11.315120324302569 26.047336589080288" stroke-width="9" stroke-dasharray="168.16760675098308" stroke-dashoffset="2.842170943040401e-14" stroke="#a3bfff" stroke-linecap="round" fill="none" style="transition: stroke-dashoffset 500ms ease-out 0s;"></path>
      <path d="M 11.315120324302569 26.047336589080288 A 45.5 45.5 0 0 1 95.5 49.999999999999986" stroke-width="9" stroke-dasharray="117.71732472568812" stroke-dashoffset="0" stroke="#66bb6a" stroke-linecap="round" fill="none" style="transition: stroke-dashoffset 500ms ease-out 0s;"></path>
    <text transform="translate(50)" x="0" y="50">
      <tspan text-anchor="middle" class="tc-label-value">85</tspan>
      <tspan class="label-text" text-anchor="middle" x="0" y="50" dy="15">Text in SVG</tspan>       
    </text>
 </svg>
  <p class='par'>Text Paragraph</p>
</div>


推荐阅读