Auto height for a foreignObject in SVG

2019-04-28 15:42发布

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.

标签: svg
2条回答
该账号已被封号
2楼-- · 2019-04-28 15:48

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.

查看更多
Juvenile、少年°
3楼-- · 2019-04-28 16:06

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>
查看更多
登录 后发表回答