69

HTML5 supports the <svg> tag, allowing to embed SVG into HTML.

Digging a little deeper, can I nest some HTML inside my <svg> fragment? For example, I'd like to put a CSS'ed <table> in some part of my SVG graphics.

I made a small test and Chrome12 didn't like the HTML <p> inside the <svg>. Is there some technique to make it work (such as maybe an html container tag?)?

Stephane Rolland
  • 38,876
  • 35
  • 121
  • 169
Serge Wautier
  • 21,494
  • 13
  • 69
  • 110

3 Answers3

64

Yes, with the <foreignObject> element, see this question for some examples.

Alternatively, if you have an html5 document you can also use CSS positioning and z-index to make parts of html visible where you want laid out on top of the svg. If you do it like that you don't need to nest the html inside the svg fragment. This will give you the most consistent behaviour across browsers in my experience.

Community
  • 1
  • 1
Erik Dahlström
  • 59,452
  • 12
  • 120
  • 139
  • 1
    Thanks Eric! [This article gives examples](http://ajaxian.com/archives/foreignobject-hey-youve-got-html-in-my-svg). FWIW, Chrome appears to be buggy (anything after a ``tag is ignored. FF5 seems to do a very good job. – Serge Wautier Jun 30 '11 at 19:40
  • 1
    For others: my mistake was not giving the foreignObject a width and height. – pedz Jul 09 '14 at 21:05
  • @Erik Dahlström, have you got a sample on how you wold put html inside svg without nesting? – woodz Feb 06 '21 at 15:38
13

Copied from bl.ocks.org (thank you, Janu Verma)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>HTML inside SVG</title>
    <style type="text/css"></style></head>
    <body>
        <div>I'm a div inside the HTML</div>
        <svg width="500" height="300" style="border:1px red solid" xmlns="http://www.w3.org/2000/svg">
            <foreignobject class="node" x="46" y="22" width="100" height="100">
                <div style="border:1px green solid">I'm a div inside a SVG.</div>                
            </foreignobject>
            <circle cx="100" cy="160" r="50" fill="blue"></circle>
        </svg>
        <div>Interesting! But you a Foreign Object.</div>
    </body>
</html>

UPDATE

Note that there is a 'camel error' in the above - it's supposed to be foreignObject (capital O), not foreignobject. It doesn't matter if the misspelling is in 'straight' HTML/SVG. But if you use JavaScript (.createElementNS), then it won't work without proper camel case (April 2020)

mathheadinclouds
  • 3,507
  • 2
  • 27
  • 37
7

Foreign Objects are not supported on Internet explorer. Please check ForeignObject

atluriajith
  • 762
  • 3
  • 17
  • 41