Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto height for a foreignObject in SVG

Tags:

svg

I have, in my SVG, a foreignObject which contains a p element. I want the height of this structure to be adapted to the height of my text.

The p element is already adapted : I've done nothing for that.

But I have troubles for the foreignObject. If I remove the field height, it doesn't work. height:auto doesn't work either.

like image 920
Arnaud Avatar asked Apr 27 '13 16:04

Arnaud


2 Answers

Since there is no real use of scaling up and down the foreignObject itself, then you can set both foreignObject height and width to 1, and via CSS set foreignObject { overflow: visible; } to make its content visible whatever it is and do whatever you need to do it with it.

like image 75
mahish Avatar answered Nov 15 '22 17:11

mahish


You can set height of the foreignObject element in em units, maybe that could help?

Right now the width and height attributes of a foreignObject are required, and must have values > 0, otherwise the element will not be rendered.

Update: An alternative is to just set the dimensions of the foreignObject to 100%, and use the fact that the foreignObject has a transparent background per default. Since other elements in svg are laid out in an absolute manner anyway they don't depend on the foreignObject size.

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <style>
    p { position: absolute; top: 50%; left: 50%; width: 100px; }
  </style>

  <circle cx="50%" cy="50%" r="25%" fill="lightblue"/>

  <foreignObject width="100%" height="100%">
    <p xmlns="http://www.w3.org/1999/xhtml">
        some wrapped text...
        some wrapped text...
        some wrapped text...
        some wrapped text...
    </p>
  </foreignObject>
</svg>
like image 11
Erik Dahlström Avatar answered Nov 15 '22 17:11

Erik Dahlström