0

I really know nothing about SVG but I need to use it for an app I'm building. So some help getting started would be really appreciated.

I want to nest a div inside of an SVG shape, which I would imagine would work like this:

<svg width="250" height="250" viewBox="0 0 250 250">
  <rect x="0" y="0" width="100" height="100" fill="red">
    <foreignObject width="100%" height="100%">
      <div>TEST</div>
    </foreignObject>
  </rect>
</svg>

But as you see, it only renders the rect element.

Even if I try only using text, then it still doesn't appear, as you can see:

<svg width="250" height="250" viewBox="0 0 250 250">
  <rect x="0" y="0" width="100" height="100" fill="red">
    <text x="50%" y="50%">TEST 2</text>
  </rect>
</svg>

So what am I doing wrong here? Why don't SVG elements appear when nested inside of other SVG elements? And how can I make them do so?

Thank you

Z_z_Z
  • 1,057
  • 4
  • 12
  • 22
  • Well that doesn't really solve the problem of nesting since the rect would be self-closing and would not be able to nest children, right? – Z_z_Z Jan 06 '19 at 20:48

1 Answers1

3

SVG only allows specific elements to be containers. Some of the most common in general use the <g> element and the <svg> element. Other containers serve specific purposes.

All SVG elements are basically positioned absolutely, there's no concept of reflow in SVG so you can put things as siblings and place them wherever you want. You simply don't need to nest things as you would in HTML.

Robert Longson
  • 118,664
  • 26
  • 252
  • 242
  • Thanks for the info. So how would you recommend positioning sibling elements so that one is always inside of another element? Because eventually I am going to be dragging the container elements around and I want the contents to drag with it – Z_z_Z Jan 06 '19 at 20:45
  • you'd have to implement some specific logic in the drag code to prevent the element that's supposed to stay inside the larger element from being repositioned so that it appears outside. – Robert Longson Jan 06 '19 at 20:46
  • I see. Thanks for the help – Z_z_Z Jan 06 '19 at 20:48
  • @RobertLongson is it possible to send you a quick email about a potential consulting job? couldn't find contact info on your website. please note when you see this, so the comment can get deleted and not clutter the page. thanks so much for all your help in the past and contributions to SVG. – Crashalot Jan 07 '19 at 20:27