Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML inside SVG

Tags:

html

svg

I would like to add some HTML markup in an SVG drawing.

html-in-svg

As far as I know, this is not possible with SVG.

The image gets displayed in the browser.

Is there a way to paint the HTML above the SVG?

Since I want to use the CSS/table features of HTML the SVG <text> element is not enough.

like image 504
guettli Avatar asked Nov 08 '19 13:11

guettli


2 Answers

User @enxaneta pointed me to foreignObject.

It works fine (even in webbrowser Edge).

<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <style>
div {
  color: white;
  font: 18px serif;
  height: 100%;
  overflow: auto;
}
  </style>
 
  <polygon points="5,5 195,10 185,185 10,195" />

  <!-- Common use case: embed HTML text into SVG -->
  <foreignObject x="20" y="20" width="160" height="160">
<!--
  In the context of SVG embedded in an HTML document, the XHTML 
  namespace could be omitted, but it is mandatory in the 
  context of an SVG document
-->
<div xmlns="http://www.w3.org/1999/xhtml">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  Sed mollis mollis mi ut ultricies. Nullam magna ipsum,
  porta vel dui convallis, rutrum imperdiet eros. Aliquam
  erat volutpat.
</div>
  </foreignObject>
</svg>

CodePen: https://codepen.io/guettli/pen/RwwBxQL

like image 72
guettli Avatar answered Nov 11 '22 17:11

guettli


There you go!

.wrapper{
    position: relative;
    width: 100px;
    height: 100px;
}
.text{
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    top: 0px;
    bottom: 0px;
    left: 0px;
    right: 0px;
    color: white;
}
<html>
<body>

<div class="wrapper">
<svg width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="red" stroke-width="4" fill="blue" />
</svg>
<div class="text">
TEXT
</div>
</div>

</body>
</html> 
like image 33
Ood Avatar answered Nov 11 '22 19:11

Ood