Design tools optimize SVG exports for round-trip re-editing, not for browser parsing. A single 24-pixel icon exported from Adobe Illustrator or Figma routinely carries XML declarations, xmlns:xlink legacy namespaces, <metadata> blocks, unapplied <defs>, nested identity-matrix <g> wrappers, and 6-decimal coordinates like 14.333333—turning a 220-byte vector into a 2.8 KB payload.
While running a quick pass in our browser-based SVG Code Optimizer & Minifier is ideal for individual assets, teams managing dozens of icons and diagrams need a deterministic svgo.config.mjs pipeline that shrinks bytes without breaking viewBox responsiveness, colliding <linearGradient> IDs, or stripping accessibility labels.
1. What Safe SVG Minification Actually Removes
Not all byte reductions are equal. Safe production optimization targets five high-waste categories inside exported XML:
| Optimization Pass | Typical Savings | Risk Level | Notes & Guardrails |
|---|---|---|---|
| Strip Editor Metadata & Comments | 15% – 35% | Zero | Removes <?xml?>, <!DOCTYPE>, <metadata>, Inkscape/Illustrator namespaces |
Coordinate Float Precision (2) |
20% – 35% | Very Low | Safe for viewBox >= 0 0 16 16; use 3 only for tiny 0 0 1 1 normalized paths |
Collapse Empty & Redundant <g> |
5% – 15% | Low | Do not collapse groups carrying id or class hooks targeted by CSS/JS animations |
Merge Static <path> Siblings |
5% – 12% | Medium | Only merge paths sharing identical fill, stroke, and opacity that never animate separately |
| Namespace / Prefix Internal IDs | +1% bytes | Critical Fix | Prevents url(#grad1) collisions across multiple inline SVGs on one HTML page |
2. Battle-Tested svgo.config.mjs for Component Libraries
Drop this configuration into the root of any Astro, Next.js, Vite, or static repository using svgo (v3.2+):
// svgo.config.mjs
export default {
multipass: true,
js2svg: {
indent: 2,
pretty: false,
},
plugins: [
{
name: 'preset-default',
params: {
overrides: {
// NEVER strip viewBox — required for responsive CSS width/height scaling
removeViewBox: false,
// Keep <title> and <desc> when authored intentionally for screen readers
removeTitle: false,
removeDesc: false,
// Round path & transform decimals to 2 places
cleanupNumericValues: {
floatPrecision: 2,
},
convertPathData: {
floatPrecision: 2,
},
},
},
},
// Remove fixed width/height only on responsive icons if desired, or keep for zero-CLS
'removeDimensions',
// Prefix internal gradient/clipPath IDs with filename hash to prevent DOM collisions
{
name: 'prefixIds',
params: {
delim: '-',
prefixClassNames: false,
},
},
],
};
Important CLS Caveat on
removeDimensions: If you stripwidthandheightattributes from inline SVGs so CSS utility classes (w-5 h-5) control sizing, make sure your stylesheet loads synchronously in<head>. If CSS fails or loads asynchronously, an inline<svg>with aviewBoxbut nowidth/heightexpands to 100% of container width, triggering a huge flash of giant unstyled icons! Settingwidth="20" height="20"in HTML while overriding with CSS classes gives you zero CLS even before CSS finishes parsing.
3. Preventing the Inline Gradient & Mask Collision Bug
One of the hardest-to-spot SVG bugs in Single-Page Applications happens when two different components render inline SVGs exported from Figma. Figma names the first linear gradient in every frame paint0_linear_1_2 or clip0.
<!-- Header Logo SVG -->
<svg viewBox="0 0 32 32">
<defs><linearGradient id="brandGrad"><stop stop-color="#2563eb"/></linearGradient></defs>
<rect width="32" height="32" fill="url(#brandGrad)" />
</svg>
<!-- Footer Badge SVG on the SAME page — accidentally reuses #brandGrad! -->
<svg viewBox="0 0 32 32">
<defs><linearGradient id="brandGrad"><stop stop-color="#0d9488"/></linearGradient></defs>
<circle cx="16" cy="16" r="16" fill="url(#brandGrad)" /> <!-- Renders BLUE (#2563eb), not TEAL! -->
</svg>
Even worse, if the Header Logo sits inside a collapsed mobile drawer (display: none), url(#brandGrad) resolves to the hidden <defs> node and both icons turn completely invisible in several browser builds! Always run prefixIds or replace simple single-stop fills with CSS currentColor.
4. Hardware-Accelerating Animated SVG Nodes
When animating inline SVG parts (such as loader spinners, chart bars, or hover chevrons), avoid mutating the d="..." attribute in JavaScript requestAnimationFrame loops unless true shape morphing is required. Mutating d invalidates geometry caches and forces main-thread path re-tessellation on every frame.
Instead, promote moving <g> or <path> elements onto the compositor using CSS transform and transform-box:
.icon-chevron-arrow {
/* Anchor transform origin to the path's own bounding box, not the 0,0 SVG canvas corner */
transform-box: fill-box;
transform-origin: center;
transition: transform 180ms cubic-bezier(0.22, 1, 0.36, 1);
}
button:hover .icon-chevron-arrow {
transform: translateX(3px);
}
Pair this workflow with our SVG Icon Sprite vs Inline Components Guide to decide which vectors belong inline and which belong in cached sprite sheets.
5. Deep Dive: Path Command Compression (d Attribute Internals)
Where does convertPathData in SVGO actually find 25% to 40% of its character savings? Inside raw SVG <path d="..."> strings, design tools emit verbose absolute commands with redundant whitespace and leading zeros. Understanding SVG path micro-syntax helps you audit minified output without breaking complex compound shapes:
- Relative vs. Absolute Coordinates (
lvsL,cvsC): An absolute command at the right side of a1440pxcanvas writesL 1384.25 912.50(16 characters). Switching to a relative delta from the previous anchor writesl 12.25-4.5(11 characters—eliminating spaces before negative signs and omitting leading zeros on decimals like.5instead of0.5!). - Horizontal & Vertical Shorthands (
H/handV/v): AnyL x ysegment whoseycoordinate equals the current penycollapses intoH x, cutting coordinate tokens in half on rectangular UI frames and bar charts. - Smooth Cubic/Quadratic Reflections (
S/sandT/t): When symmetric Bezier handles mirror across an anchor node,SandTinfer the first control point automatically from the preceding segment.
<!-- Verbose Illustrator Path (98 chars) -->
<path d="M 10.00,20.00 L 90.00,20.00 L 90.00,60.00 L 10.00,60.00 L 10.00,20.00 Z" />
<!-- Equivalent Minified Path Syntax (21 chars — 78% smaller, 100% identical geometry) -->
<path d="M10 20h80v40H10z" />
6. When NOT to Merge Paths or Strip IDs
Aggressive manual minification breaks three specific interactive workflows unless guarded carefully:
- Stroke-Dashoffset Line-Drawing Animations: Animating
stroke-dasharrayandstroke-dashoffsetrelies onSVGGeometryElement.getTotalLength()per<path>. Merging three separate strokes into one compound<path>alters their combined path length and causes all segments to draw sequentially instead of simultaneously. - Anchored Tooltip Targets in Interactive Maps: Floorplans and choropleth maps attach data attributes or IDs (
id="region-pk-isb") to individual<path>elements. EnablingcleanupIdswithout anpreservePrefixes: ['region-']allowlist renamesid="region-pk-isb"toid="a", breaking click handlers. - CSS
fill-rule: evenoddCutouts: Donut icons and hollow badges rely on winding direction (nonzerovsevenodd). If an icon turns solid black after optimization, inspect whether an inner cutout subpath lost its reverse winding order or explicitfill-rule="evenodd".
| Symptom After Optimization | Root Plugin / Cause | Exact Fix in svgo.config.mjs |
|---|---|---|
Icon refuses to scale with CSS w-6 h-6 |
viewBox missing, hardcoded width/height |
Keep removeViewBox: false and add viewBox="0 0 W H" |
Inner hole of 'O' or donut icon fills solid |
fill-rule="evenodd" stripped or path merged |
Disable mergePaths on compound boolean icons |
| Second inline SVG renders wrong gradient color | Duplicate id="a" across two SVGs on page |
Enable prefixIds plugin with unique file prefix |
| Animated stroke morph snaps or glitches | convertShapeToPath / convertPathData altered vertex count |
Add a data-no-optimize check or skip morph targets |
For one-off assets where you want visual verification right beside the minified XML string, paste your raw vector into our SVG Code Optimizer & Minifier and toggle each cleanup pass live.