Embedding SVG

Inline SVG, `<img>`, Backgrounds and Sprites

An <img> or CSS background loads SVG as a sealed picture: it caches as a file and runs no scripts, but page CSS cannot reach inside, and currentColor in it falls back to black. Inline SVG is part of the DOM, styleable and scriptable, but repeats its bytes on every page. <object> and <iframe> load it as a separate document whose own scripts run. A CSS mask sits between: the icon is a stencil that background-color paints.

One currentColor icon embedded four ways, all in rust-colored textHTMLLive
<style>
  div { display:inline-block; width:110px; text-align:center; font:12px Arial; color:#b5452f }
  div > * { width:48px; height:48px; display:block; margin:0 auto 6px }
  .bg { background:var(--icon) center/contain no-repeat }
  .mask { background:currentColor; mask:var(--icon) center/contain no-repeat }
</style>
<div><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
  <circle cx="10.5" cy="10.5" r="6.5"/><path d="M15.5 15.5 21 21"/></svg>inline</div>
<div><img id="img">img</div><div><span class="bg"></span>background</div>
<div><span class="mask"></span>mask</div>
<script>
  const svg = document.querySelector('svg').outerHTML
    .replace('<svg', '<svg xmlns="http://www.w3.org/2000/svg"');
  const url = 'data:image/svg+xml,' + encodeURIComponent(svg);
  img.src = url;
  document.body.style.setProperty('--icon', `url("${url}")`);
</script>
Browser output of Listing 1.14
Browser output of 14

Only the inline copy and the mask follow the text color. Masks are the usual way to ship recolorable icons in CSS alone, <symbol> sprites the way in HTML.