How to make svg size to fit content text

448 views Asked by At

Please check my code link

<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>

How can I set the width and height of SVG tag to fit its content (the tspan tags). The number of tspan tags is not fixed.

Thanks

1

There are 1 answers

1
enxaneta On

First: you are using an invalid viewBox attribute. No percentages are allowed. The value of the viewBox is fromX fromY width height.

I am using a viewBox where the width is 41 - the width of the bounding box of the text.

Second: I suspect you intend to cut the text from the last rect. In this case you need the text to be white.

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>