1

I'm creating an SVG with a few rects dynamically .

Inside of a rect there's a text which its width can change.

I want the width of the rect to adjust according to the length of the text.

I s it possible or what are the workarounds?

Here's a fiddle with a simple example:

Fiddle

Here's the SVG:

  <div class="container">
   <svg height="180" width="500">
      <g transform="translate(100, 50)">
         <rect width="100%" class="node" rx="17" height="30" style="fill: rgb(255, 255, 255); cursor: default;"></rect>
         <circle cx="15" cy="15" r="15" fill="#FFFFFF" filter="url(#circleShadow)" stroke="lightgray" stroke-width="0.1" width="15" height="15"></circle>
         <text x="40" y="19" class="graph-element-text node-text-color" style="cursor: pointer;">long text11111111111111122222</text>
      </g>
   </svg>
</div>
Ace
  • 831
  • 2
  • 8
  • 28
  • 1
    like [this](https://stackoverflow.com/a/31013492/1038015) perhaps? – Robert Longson Mar 18 '22 at 15:39
  • @RobertLongson - I'm not sure how's that related to my situation. I'm building an SVG dynamically in code and the text child element width can change and I need the rect to display all the text. – Ace Mar 18 '22 at 16:45
  • 1
    And why do you think that's not related to your situation? – Robert Longson Mar 18 '22 at 18:40
  • @RobertLongson - my bad - I missed that part. The foreignObject solution worked. Thanks! – Ace Mar 19 '22 at 15:43

1 Answers1

1

As @Robert Longson implied: you have to mimic a <div> like display of text boxes in svg, since <text> elements don't have any auto-growing capabilities. (at least not comparable to html block elements).

Actually, there a <rects> can't wrap a text element (like e.g. a div)

A workaround might be using a foreign object:

.container {
  background-color: lightgray;
}


.graph-background-color {
    background-color: #F8F8F9;
}

svg {
  fill: yellow;
  display:inline-block;
}


.text-wrp{
    text-align:center;
}
.inner-text{
  text-align:center;
  background:#fff;
  width:auto;
  display:inline-block;
  text-align:center;
  padding:0.5em 0.5em 0.5em 2em;
  height:30px;
  font-size:15px;
  line-height:1.75em;
  border-radius: 2em 0 0 2em
}
<div >
  <svg class="container" height="180" width="500">
    <g>
      <foreignObject x="50%" y="50%" width="50%" height="50" style="transform:translateX(-25%) translateY(-15%)">
        <div class="text-wrp" xmlns="http://www.w3.org/1999/xhtml">
          <div class="inner-text" xmlns="http://www.w3.org/1999/xhtml">
            long text11111111111111122222</div>
          </div>
      </foreignObject>
    </g>
  </svg>
</div>

<foreignObject> might introduce issues, when your svg needs to be standalon (e.g. should also be editable in an editor like Ai, inkscape).

herrstrietzel
  • 11,541
  • 2
  • 12
  • 34