Taking SVG “screenshots” of HTML elements

[2025-09-29] dev, html, css, javascript, svg
(Ad, please don’t block)

I was looking for a way to create images (think screenshots) of CSS layouts that I can use in HTML, EPUB and PDF files. This blog post describes my solution – which produces SVG images.

Two JavaScript libraries that convert HTML to SVG  

Both are useful, but the latter library works much better for my use case.

Creating a web page full of SVG screenshots  

I use html-to-svg as follows (check out my solution online): A file can contain zero or more sections with CSS layout demos. This is an example of such a section:

<h2><code>box-sizing</code></h2>
<section id="css-box-sizing">
  <style>
    .outer {
      ...
    }
  </style>
  <div class="outer">
    ...
  </div>
</section>

JavaScript code iterates over the sections and adds a <details> element:

▶︎ Download css-box-sizing.svg

  • If you expand the details, you can see the generated SVG image. That lets you compare it with the HTML, etc.
  • If you click on the download link, the browser downloads an SVG file to your disk.
    • The SVG filename is derived from the section’s ID.
    • The browser uses that filename because it’s the value of the download attribute of the link.
    • The href of the link is set up like this:
      const fileBlob = new Blob(
        [svgElement.outerHTML], { type: 'text/plain' }
      );
      link.href = URL.createObjectURL(fileBlob);