首页 > 解决方案 > 如何使 svg 大小适合内容文本

问题描述

请检查我的代码链接

<div class="suj_content">
<header class="suj_content_hd">
                        <div id="suj_content_hd_ytb"><iframe class="suj_content_hd_ytb" src="https://www.youtube.com/embed/kOc6ME2J_Us?mute=1&amp;loop=1&amp;playlist=kOc6ME2J_Us&amp;autoplay=1&amp;showinfo=0&amp;controls=0" width="100%" height="100%" frameborder="0"></iframe></div>
                        <h2>
    <svg id="suj_content_svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100% 100%" preserveAspectRatio="xMidYMid slice">
        <defs>
            <mask id="mask" x="0" y="0" width="100%" height="100%">
                <rect x="0" y="0" width="100%" height="100%"></rect>
                <text>
                    <tspan x="0" dy="33.333333333333%" alignment-baseline="middle" text-anchor="start">mittel</tspan><tspan x="0" dy="23.222222222222%" alignment-baseline="middle" text-anchor="start">stand</tspan><tspan x="0" dy="23.222222222222%" alignment-baseline="middle" text-anchor="start">digital</tspan>                 </text>
            </mask>
        </defs>
        <rect x="0" y="0" width="100%" height="100%"></rect>
    </svg>
    </h2>
</header>

如何设置 SVG 标签的宽度和高度以适合其内容(tspan 标签)。tspan 标签的数量不固定。

谢谢

标签: htmlcsssvgtspan

解决方案


首先:您使用了无效的 viewBox 属性。不允许使用百分比。viewBox 的值为fromX fromY width height

我正在使用宽度为 41 的 viewBox - 文本边界框的宽度。

第二:我怀疑您打算从最后一个矩形中删除文本。在这种情况下,您需要将文本设为白色。

console.log(t.getBBox())
text{font-size:16px;}
<svg id="suj_content_svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 41 50" preserveAspectRatio="xMidYMid slice">
  <defs>
    <mask id="mask" x="0" y="0" width="100%" height="100%">
      <rect x="0" y="0" width="100%" height="100%"></rect>
      <text fill="white" id="t">
        <tspan x="0" dy="25%" dominant-baseline="middle" text-anchor="start">mittel</tspan>
        <tspan x="0" dy="25%" dominant-baseline="middle" text-anchor="start">stand</tspan>
        <tspan x="0" dy="25%" dominant-baseline="middle" text-anchor="start">digital</tspan>
      </text>
    </mask>
  </defs>
  <rect x="0" y="0" width="100%" height="100%" mask="url(#mask)"></rect>
</svg>


推荐阅读