0

It is necessary that the text fills the svg as much as possible as with bacground-size: contain. The svg parent can be resized dynamically. The text is always single line. Now such a solution is used using js, but it is desirable to do it using the svg itself.

const $svg = document.querySelector(`svg`);
const $text = $svg.querySelector('text');
const $input = document.querySelector('input');

$input.addEventListener('input', e => {
  $text.textContent = e.target.value;
  const box = $text.getBBox();
  $svg.setAttribute('viewBox', `${box.x} ${box.y} ${box.width} ${box.height}`);
});

$input.dispatchEvent(new Event('input'))
svg {
  border: 1px solid red;
  height: 10em;
  width: 100%;
}
<svg preserveAspectRatio="xMaxYMid meet">
<text alignment-baseline="baseline" dominant-baseline="middle" text-anchor="middle" fill="black"></text>
</svg>
<input type='text' value='Random single line text'>
nazarpunk
  • 187
  • 1
  • 1
  • 7
  • CSS Tricks did a [post](https://css-tricks.com/fitting-text-to-a-container/) on this a few years back, not sure that anything has changed since. It's pretty much either magic numbers or Javascript, if you want dynamic then you need JS, why would you not want to use JS though? – JHeth Jun 03 '21 at 19:09
  • Paul answered that one a year ago: https://stackoverflow.com/questions/34298838/svg-responsive-text – Danny '365CSI' Engelman Jun 03 '21 at 19:14
  • This answer not work with very long or short text. CSS Tricks use magick number, this now work for me. – nazarpunk Jun 03 '21 at 19:44

1 Answers1

0

Can you not just use a parent div? Add a no wrap attribute (word-break or flex-wrap for a flex container) to the text and that will stretch the div to full text width. Then make the svg width: 100% within the div.

David Min
  • 1,246
  • 8
  • 27