Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

How to use HTML with CSS inside SVG

Have you ever run into a situation where you want to render some HTML into an SVG? Well, if you ask me the same question, I would say yes.

There is a legitimate use-case where you would want this behavior. For instance, if you’ve ever worked with GitHub readme files, which are essentially written in Markdown, you might be knowing that you can use HTML into the readme but you can not actually use CSS to apply style changes to the HTML directly. It would be useful if you could do so, right?

The <foreignObject> element

This can be solved by using the <foreignObject> SVG element in which you can add an HTML under a different namespace than the parent SVG and then you can also style the elements using CSS like so.

<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <style>
    div {
      background: pink;
      font: 12px serif;
      padding: 10px;
    }
    
    .red {
      color: red;
    }
    
    .green {
      color: green
    }
  </style>

  <foreignObject x="20" y="20" width="160" height="100">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <p class="red">This is red color</p>
      <p class="green">This is green color</p>
    </div>
  </foreignObject>
</svg>

Here’s how the output would look like.

See the Pen SVG With CSS by Amit Merchant (@amit_merchant) on CodePen.

If you want to see this in action on a GitHub readme, you can check out this repository by Sindre Sorhus who has proposed this idea.

The element also has a fair amount of support for all modern browsers as of today. So, no issues there.

Data on support for the mdn-svg__elements__foreignObject feature across the major browsers from caniuse.com

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?