Inline SVG Sprites in HTML

Learn how to embed SVG sprites directly in your HTML document for zero-latency icon rendering. Understand placement, visibility hiding, and the tradeoffs versus external sprite files.

Implementation

Detailed Explanation

Inline SVG Sprites

An inline SVG sprite is embedded directly in your HTML document, typically right after the opening <body> tag. This approach eliminates the need for an additional HTTP request to load the sprite file, providing instant icon rendering.

Basic Structure

<body>
  <!-- Hidden SVG sprite -->
  <svg xmlns="http://www.w3.org/2000/svg"
       style="display:none">
    <symbol id="icon-home" viewBox="0 0 24 24">
      <path d="M3 12l2-2m0 0l7-7 7 7M5 10v10..."/>
    </symbol>
    <symbol id="icon-search" viewBox="0 0 24 24">
      <circle cx="11" cy="11" r="8"/>
      <path d="m21 21-4.3-4.3"/>
    </symbol>
  </svg>

  <!-- Use icons anywhere -->
  <nav>
    <svg width="20" height="20">
      <use href="#icon-home"/>
    </svg>
    Home
  </nav>
</body>

Hiding the Sprite

The sprite container must be hidden so it does not take up space in the layout. There are several approaches:

  • style="display:none" — Most common. Removes the element from layout entirely. Works in all browsers.
  • hidden attribute — HTML5 semantic hiding. Equivalent to display:none in most browsers.
  • width="0" height="0" with aria-hidden="true" — Used when display:none might cause issues with some SVG rendering engines.

Avoid using visibility:hidden as it still takes up space in the layout.

Placement

Place the sprite early in the document (immediately after <body>) so that all <use> references can find their symbols. If the sprite appears after a <use> reference in the HTML, the browser may not render the icon until the sprite is loaded and parsed.

Advantages

  1. Zero-latency rendering — Icons are available as soon as the HTML is parsed, with no additional network request
  2. No cross-origin issues — Everything is in the same document
  3. Works with CSP — No external file to whitelist
  4. No caching complications — The sprite is part of the page

Disadvantages

  1. No caching across pages — The sprite markup is repeated on every page, increasing each page's HTML size
  2. Cannot be loaded asynchronously — The sprite blocks rendering if placed in the head
  3. Increases initial HTML size — For large icon sets (100+ icons), this can add 50-100 KB to every page

When to Use Inline Sprites

Inline sprites are best for small-to-medium icon sets (under 50 icons) on single-page applications where the HTML is loaded once and the icons need to render instantly without any flash of missing content.

Use Case

Single-page applications, landing pages, and projects where icon rendering speed is critical and the icon set is small enough that the HTML size increase is acceptable.

Try It — SVG Sprite Generator

Open full tool