SVG: fixed font size

I'd recommend nested SVG tags. You can keep your outermost SVG without viewBox and add all text under this tag, while adding a second SVG to cover the full area but using a viewBox.

You'll need to change positions for the text from absolute to relative values, but it works quite well.

That way your text will change position with the svg size but not scale the text. The inner SVG will, though, since you set a viewBox.

Example: JS for variable container, SVG always fills the div. The scaling is pure SVG.

function changeCircleDiv(element) {
  s = document.getElementById("container").style;
  s.width = element.value + 'px';
  s.height = s.width;
}
body {
  font-size: 2em;
}
<input type="number" onchange="changeCircleDiv(this);" value="100"></input>
<div id="container" style="width: 100px; height: 100px;">
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%">
        <svg width="100%" height="100%" viewBox="0 0 20 20">
            <circle cx="10" cy="10" r="8" stroke="black" fill="none"/>
        </svg>
        <text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">Center</svg>
    </svg>
</div>

In the end...

I have removed text from svg and added div text block with absolute positioning inside shared html container. That worked prefect. Div's appearance is controlled over css with media queries - it is independent from svg scaling.

Your can see diagram in action at: https://www.xtech.pl/jak-to-dziala-dla-dostawcy (scroll down to second section on the page, then you can resize your screen to see how it works).


The short answer is no.

If the text is in an SVG with a viewBox, and the SVG gets scaled, its contents get scaled also. There is no way to make the text have a "global" size that is unaffected by the SVG scaling.

The only possible solution would be calculate the scaling factor using Javascript and dynamically update the font size every time the SVG size changed.


You can do it in this way "Responsive SVG with sticky text" See here: https://bl.ocks.org/veltman/5cd1ba0b3c623e7b5146

Or... if you want to use media queries for font in SVG, the answer is yes. Run this code snippet.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100%" height="200px">
  <style>
    text {
      font-size: 10px;
    }

    @media (max-width: 600px) {
      text {
        font-size: 20px;
      }
    }

    @media (max-width: 800px) {
      text {
        font-size: 16px;
      }
    }

  </style>
  <circle cx="50" cy="50" r="50" fill="orange"/>
  <text x="50" y="60" text-anchor="middle">Testing</text>
</svg>

Tags:

Html

Css

Svg