How HTML to SVG Conversion Works
HTML describes a page with elements that the browser lays out. SVG describes shapes and has no layout engine of its own. The standard way to put HTML inside an SVG is the foreignObject element. This html to svg converter wraps your markup in one, so the browser still lays out the text, boxes and styles.
<svg xmlns="http://www.w3.org/2000/svg" width="800" height="120" viewBox="0 0 800 120">
<foreignObject x="0" y="0" width="800" height="120">
<div xmlns="http://www.w3.org/1999/xhtml">Hello</div>
</foreignObject>
</svg>Three details make this work reliably. The wrapper must declare the XHTML namespace. The HTML must be well-formed XML, with every tag closed and entities written the XML way. And the SVG needs a width and height that fit the content. The tool takes care of all three: it re-writes your HTML as valid XML, adds the namespace and measures the real height by laying the content out at your chosen width.
What Is Kept, What Is Removed
- Kept: text, headings, lists, tables, images, inline styles, class names and <style> blocks.
- Removed for safety: script, iframe, object, embed, link, meta, base and form elements, all on-event attributes such as onclick, and javascript: links. An SVG opened directly in a browser can run script, so the tool never writes it.
- External CSS files and web fonts are not fetched, so put the CSS in a <style> block and use fonts that are installed on the viewer's device.
When This Is Useful
- Social cards and badges: design a card in HTML and CSS, wrap it as an SVG and serve it as an image from your own site.
- README and documentation graphics: SVG files render inside many docs pages and keep their styling.
- Export to an image: wrap the HTML as an SVG, then turn it into a PNG with SVG to PNG inside the same browser.
- Learning: see exactly how the XHTML namespace and foreignObject fit together.
If the SVG has to be embedded in CSS or a JSON file, URL Encode and Base64 Encode turn it into a safe data URI string.
Tips for a Clean Result
- Close all tags and quote all attributes. Fragments such as <br> are written as <br /> automatically.
- Give the outer element an explicit font-family and font-size. The SVG does not inherit your website's styles.
- Use pixel units for widths. Percentages are relative to the canvas width you chose.
- Embed images as data URIs. Images from other sites may be blocked when the SVG is used as an image.