Z_z_Z
Z_z_Z

Reputation: 1107

Basic SVG - How to nest elements?

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

Upvotes: 1

Views: 1498

Answers (1)

Robert Longson
Robert Longson

Reputation: 124029

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.

Upvotes: 4

Related Questions