How exactly does the fontSize of SVG foreignObject work

860 views Asked by At

New to SVG, I was trying to use foreignObject to put a custom HTML component inside SVG, and I'm very confused about the fontSize.

It seems like the usual CSS like font-size: 10px doesn't work the same way here, when I add that style, the font I got is not exactly 10px. Besides, I noticed that the font size changes as the screen width change.

My question is, which factors are affecting the font size here? and how do I get a static style like 14px?

Here's my current code:

<div style="width: 100%">
  <svg class="ProgressBar" viewBox="0 0 120 10">
    <foreignObject height="30" width="50" x="0" y="0">
      <div style="font-size: 10px; color: rgb(135, 144, 162);">
        <div>Text</div>
      </div>
    </foreignObject>
  </svg>
</div>

1

There are 1 answers

2
Paul LeBeau On

Like any other SVG element, <foreignObject> elements are subject to any scaling that the SVG undergoes.

Your SVG has a viewBox, so the contents will be scaled. That includes the foreignObject and the text within it.

If you don't want scaling, then remove the viewBox. Or set the SVG width and height so that the SVG doesn't scale (ie. has 1:1 scale).

For example, the text in the following snippet has a size of 10px. This is because the width has been set to the same value as the viewBox width value (120).

<div style="width: 120px">
  <svg class="ProgressBar" viewBox="0 0 120 10">
    <foreignObject height="30" width="50" x="0" y="0">
      <div style="font-size: 10px; color: rgb(135, 144, 162);">
        <div>Text</div>
      </div>
    </foreignObject>
  </svg>
</div>