Scale the SVG form to fit the content, where the content contains foreignObject

Is there a way — preferably without using JavaScript — to put some HTML content into an SVG foreignObjectform so that the SVG form automatically resizes (or scales) to fit its contents?

those. something very vague, like this pseudo-code example, but valid and functional in the way I described:

<?xml version="1.0" standalone="yes"?>
<svg xmlns = "http://www.w3.org/2000/svg">
  <rect x="10" y="10" width="SCALE_TO_FIT_CONTENTS" height="SCALE_TO_FIT_CONTENTS" fill="gray">
    <foreignobject width="100%" height="100%">
      <body xmlns="http://www.w3.org/1999/xhtml">
        <div>Some HTML text</div>
      </body>
    </foreignobject>
  </rect>
</svg>
+5
source share
1 answer

without using javascript, you cannot do this. In fact, SVG forms cannot be used as containers. But hopefully this is what you are asking for:

<script type="text/javascript">
    function myFun(){
        var w = document.getElementById("myDiv").scrollWidth;
        document.getElementById("myRect").setAttribute("width",w);
    }
</script>
<svg xmlns = "http://www.w3.org/2000/svg" onload="myFun()">
    <rect id="myRect" x="10" y="10" width="0" height="100" fill="red"></rect>

        <foreignObject x="10" y="10" position="absolute" width="100%" height="100%">
            <div id="myDiv" style="display: inline-block;">Some HTML text that resizes its SVG container</div>
        </foreignObject>
</svg>
+2
source

All Articles