BlogImage Compression

How to Compress SVG Files Without Breaking Icons or Logos

Learn a safe SVG compression workflow for icons and logos: keep viewBox, protect IDs and gradients, use SVGO or SVGOMG carefully, and verify the result before publishing.

Updated: June 12, 2026

To compress SVG files without breaking icons or logos, use SVGO or SVGOMG with conservative settings, keep the viewBox attribute, preserve IDs used by gradients, masks, CSS, or scripts, and visually compare the optimized file against the original at small and large sizes. SVG compression works by removing unnecessary XML — metadata, whitespace, comments, and excessive numeric precision — not by discarding pixels. For static icons, start with SVGO's default preset, use 2–3 decimal precision, and disable risky ID or path cleanup when the SVG is styled or animated externally.

Key Takeaways

  • SVGs are XML text documents, not pixel grids — compression removes code bloat, not image data.
  • Never remove the viewBox attribute. It controls responsive scaling; without it your icon or logo will not adapt to different container sizes.
  • SVGO v4 (released 2024) preserves viewBox and <title> by default — a major safety improvement over earlier versions (SVGO v3→v4 migration).
  • Always visually compare the optimized output at small (16 px) and large (500 px+) sizes before publishing.
  • Code-level optimization and server-side gzip or Brotli are complementary — both are needed for the smallest transferred payload.

What Makes SVG Compression Different From Raster Compression

SVG files are XML documents that describe shapes using mathematical coordinates, paths, and styling rules. When you compress a JPEG or PNG, you are discarding pixel data — lossy compression. When you compress an SVG, you are removing unnecessary code: comments, editor fingerprints, redundant group nesting, unused <defs> entries, and coordinates with more decimal places than the human eye can detect on screen.

This means SVG compression can be truly lossless — the rendered output is identical before and after — as long as you avoid the few transforms that alter visual behavior or break external references.

A single-file example for reference: one benchmark showed a simple bookmark icon exported from Figma dropping from 1,024 bytes to 191 bytes after removing metadata and rounding coordinates (Penpot, 2025). Results vary widely depending on how much metadata your design tool embeds, the complexity of the artwork, and which plugins you enable. Do not treat any single example as a universal baseline — measure your own files before and after.

Before You Compress: Check What the SVG Depends On

Rushing into optimization without understanding the file's dependencies is the most common cause of broken icons and logos. Before running any optimizer, answer these questions:

DependencyCheck
viewBox attributePresent? (must be kept)
IDs in <defs> (gradients, masks, filters, clip-paths)Any fill="url(#...)" or clip-path="url(#...)" references?
External CSSDoes a stylesheet target element IDs or class names inside the SVG?
External JavaScriptDoes a script query or manipulate SVG elements by ID or class?
<title> / aria-labelIs the SVG conveying semantic meaning (not purely decorative)?
AnimationSMIL or CSS animations that target specific IDs or classes?
Width / Height unitsFixed px dimensions needed for cutting machines or PDF output?

If any row is "yes," the corresponding optimizer plugin must be handled carefully or disabled. The sections below map each dependency to the right plugin decision.

Safe SVG Compression: Step-by-Step Workflow

Step 1 — Save a Copy of the Original

Before any optimization, duplicate the file and keep the design-source (Figma, Illustrator, Affinity) intact. Optimization is a one-way transform — you cannot reliably reconstruct the original from the output if something goes wrong.

Step 2 — Choose Your Optimizer

ToolInterfaceLive PreviewBest For
SVGOMG (svgomg.net)Browser GUIYesOne-off files, beginners, visual verification
SVGO CLI (npx svgo)Command lineNoBatch processing, CI pipelines
Vecta NanoBrowser + APILimitedEmbedding fonts, advanced minification

For most designers and developers, SVGOMG is the safest starting point. Every optimization has a toggle and the preview updates instantly — if something breaks, you see it immediately and can disable the responsible plugin. Verify features on each tool's official page before relying on them.

Step 3 — Apply Safe Optimizations First

Enable these settings. They are generally safe for static icons and logos, but test any file that uses external CSS, scripts, filters, or animations:

  • Remove doctype — the <!DOCTYPE> declaration is unnecessary in browsers.
  • Remove XML processing instructions — the <?xml version="1.0"?> line.
  • Remove comments — designer notes, export timestamps.
  • Remove metadata — the <metadata> block recording author, tool, and timestamps.
  • Remove editor namespace data — Figma, Sketch, and Illustrator inject proprietary attributes and namespace prefixes.
  • Cleanup attribute whitespace — normalizes spacing.
  • Minify styles — shortens inline CSS.
  • Convert styles to attributes — moves style="fill:#000" to fill="#000" where possible.

Step 4 — Set Numeric Precision Carefully

Rounding coordinates is where real byte savings come from. SVG exports often carry values like 12.000000 or 16.75360107421875. Rounding to 2–3 decimal places is appropriate for most web graphics:

PrecisionTypical UseRisk
1 decimalLarge decorative illustrations onlyNoticeable curve distortion at small sizes
2 decimalsMost web icons and logos (≥ 24 px)Safe for simple shapes
3 decimalsSmall icons (< 24 px), detailed logosSafest for fine geometry
4+ decimalsAnimated paths, precision engineering artRarely needed for static icons

Start at 3 decimals. If the file is still large and the SVG looks identical at 2, drop down. Do not go below 2 for icons or logos.

Step 5 — SVGO Settings: Keep, Test Carefully, or Avoid

PluginActionReason
removeDoctypeKeep enabledAlways safe
removeCommentsKeep enabledAlways safe
removeMetadataKeep enabledAlways safe
removeEditorsNSDataKeep enabledAlways safe
cleanupAttrsKeep enabledAlways safe
minifyStylesKeep enabledSafe for inline styles
removeViewBoxDisableBreaks responsive scaling — SVGO v4 disables this by default (SVGO docs)
cleanupIdsTest carefullySafe when IDs are not referenced by external CSS, JS, or runtime code; disabling is the safest default for logos
mergePathsAvoid for logosBreaks when paths need separate colors, hover states, or animation
removeUselessDefsTest carefullyCan remove <defs> entries still needed if references are dynamic
removeHiddenElemsTest carefullyBreaks if hidden elements are toggled by JavaScript or CSS
convertPathDataTest at your precision levelCan alter curves; safe at conservative precision (≥ 2 dp)

Step 6 — Use the SVGO v4 Configuration Format

SVGO v4 uses a preset-default with overrides pattern. The old array-of-strings with type/active fields is no longer recommended. A safe starting configuration:

// svgo.config.mjs  (SVGO v4 format)
export default {
  plugins: [
    {
      name: "preset-default",
      params: {
        overrides: {
          // viewBox is preserved by default in v4 — no need to override
          // Disable cleanupIds to protect gradient and mask references
          cleanupIds: false,
          // Disable mergePaths for logos with multi-color or interactive paths
          mergePaths: false,
          // Disable removeUselessDefs when defs are referenced dynamically
          removeUselessDefs: false,
        },
      },
    },
  ],
  floatPrecision: 3,
};

For batch processing an icon set:

# Install and run on all SVGs in the current directory
npx svgo --config svgo.config.mjs *.svg

# Recursive processing
npx svgo --config svgo.config.mjs --recursive --folder ./assets/icons

Run optimization when the SVG is finalized, then commit the result. Re-optimize only if the source file changes.

Step 7 — Visually Verify the Result

Open both the original and optimized SVG side by side. Check at multiple sizes:

Pre-publish visual verification checklist:

  • 16 × 16 px — favicon and toolbar icon size; precision issues appear first here
  • 24 × 24 px — common UI icon size
  • 64 × 64 px — app icon and retina display check
  • 500 × 500 px or larger — reveals clipping, missing gradients, or lost detail
  • Dark background — shows if transparent areas or fill colors are intact
  • Light background — cross-check stroke and fill visibility
  • Actual page context — embed in HTML and test in a real browser tab
  • Response headers — confirm content-encoding: br or content-encoding: gzip if using server compression (MDN Content-Encoding)

If you used SVGOMG, toggle "Show original" to compare. For CLI workflows, open both files in browser tabs.

Step 8 — Test in Context

Drop the optimized file into your actual website or app and verify:

  • The icon or logo scales correctly when the browser window resizes.
  • Hover states, color changes, and CSS styling still work.
  • Any JavaScript that targets elements inside the SVG (by ID or class) still functions.
  • Accessibility labels (<title>, aria-label) are intact for non-decorative graphics.

Common Ways SVG Compression Breaks Icons and Logos

The viewBox Is Missing

The viewBox attribute defines the coordinate system. Without it, the SVG renders at its literal width/height pixel dimensions and cannot scale responsively. This is the most common cause of broken SVGs after compression. SVGO v4 fixed this by preserving viewBox by default (SVGO migration docs), but older tools and tutorials may still strip it.

Fix: Confirm viewBox is present after optimization. If your tool removed it, add it back manually or update to SVGO v4+.

Gradients or Fills Disappear

When an SVG uses a gradient referenced by ID — fill="url(#logoGradient)" — and the optimizer renames or removes that ID, the fill breaks silently. The path renders with no color.

Fix: Disable cleanupIds for SVGs that use gradients, masks, clip-paths, or filters defined in <defs>.

Paths Distort at Small Sizes

Aggressive decimal rounding (0–1 decimal places) can shift curve control points enough that an icon looks wrong at 16 px or 24 px but acceptable at larger sizes.

Fix: Use at least 2 decimal places for icons. Use 3 for detailed logos or icons smaller than 24 px.

Animation Targets Disappear

If your SVG has CSS or SMIL animations that target specific element IDs or class names, an optimizer may rename or remove them, breaking the animation silently.

Fix: For animated SVGs, disable cleanupIds, mergePaths, and convertPathData. Test every animation state after optimization.

Safe Settings by Use Case

Use CasePrecisionKeepAvoid
Website UI icon (16–32 px)2–3viewBox, currentColor, aria-*removeViewBox, cleanupIds
Brand logo (all sizes)3viewBox, groups, gradient IDsmergePaths, removeUselessDefs
Animated SVG3All IDs, classes, <title>convertPathData, cleanupIds, mergePaths
Illustration with gradients2–3All <defs> referencesremoveUselessDefs, cleanupIds
Favicon (single-color)2viewBoxPrecision below 2 dp
Traced raster-to-SVG2Visible paths onlyOne-click aggressive simplification

Use Gzip or Brotli After SVG Optimization

Code optimization shrinks the file on disk. Server-side compression shrinks what the browser actually downloads. Because SVGs are text, they compress well with general-purpose algorithms — but verify your server's actual behavior rather than assuming defaults, as configurations vary widely:

MethodTypical SVG ReductionNotes
GzipSignificant (varies by file content and server level)Supported by Nginx, Apache, Cloudflare, and many hosts; verify content-encoding: gzip in response headers
BrotliOften slightly better than gzipSupported by all modern browsers (MDN Brotli); verify content-encoding: br in response headers

To confirm your server is compressing SVGs, open browser DevTools → Network tab → click the SVG file → check the Content-Encoding response header. If it is absent, compression is not active for that asset type.

What to Do Next

  1. Audit your current SVGs. Anything over 2 KB for a simple icon likely has metadata bloat worth removing.
  2. Run one file through SVGOMG with the safe defaults to establish a before-and-after baseline in bytes.
  3. Add gzip or Brotli to your server if you have not already — check your hosting documentation and verify headers after enabling.
  4. For other image formats in the same workflow, tools like LessMB provide a quick browser-based compression step for supported raster formats; verify the visual output before publishing.
  5. Consider a pre-commit hook that runs SVGO on changed SVG files so no unoptimized vectors enter your repository.

FAQ

Does compressing an SVG reduce its quality?

Not when done correctly. SVG is a text-based vector format, so most compression removes invisible bloat — editor metadata, over-precise coordinates, unused definitions — without changing the rendered graphic. Problems only appear when aggressive settings alter path data, remove viewBox, or break CSS or JavaScript references.

Why did my SVG break after compression?

The most common causes are a removed viewBox attribute (breaks responsive scaling), cleaned-up IDs that gradients or masks still reference, or over-aggressive path simplification that rounds away important curve detail. SVGO v4 no longer removes viewBox by default, which eliminates the most frequent cause (SVGO migration docs).

What SVGO settings are safest for logos?

Use SVGO's preset-default with overrides to disable cleanupIds, mergePaths, and removeUselessDefs. Set floatPrecision to 3. Always keep viewBox, gradient IDs, and any IDs targeted by external CSS or JavaScript. See the configuration example in the workflow above.

Should I keep viewBox in an optimized SVG?

Yes, always. The viewBox attribute defines the coordinate system and lets the browser scale the SVG responsively. Removing it causes icons and logos to render at fixed pixel dimensions and break layouts. SVGO v4 preserves viewBox by default (SVGO preset-default docs).

Can gzip or Brotli replace SVG optimization?

No — they complement each other. Code-level optimization (SVGO) shrinks the file on disk and removes structural complexity. Server-side gzip or Brotli then compresses what the browser downloads. Both steps together produce the smallest transferred payload.

Should I convert my logo to WebP instead of SVG?

For logos and icons that need to stay sharp at any size, SVG is the better choice. WebP is a raster format — it excels at photographs but loses detail when scaled up. A well-optimized SVG is usually smaller than an equivalent WebP at the sharpness level logos require.

Can I compress SVG files without any tools?

Yes. Open the SVG in a text editor and manually remove comments (<!-- ... -->), the <!DOCTYPE> line, the <?xml?> prolog, empty <g> groups, and proprietary id="shape-..." or class="frame-..." attributes added by your design tool. You can also round long decimals in path data by hand. Manual cleanup works but is slow and error-prone for more than a few files.

What about accessibility after optimization?

Preserve the <title> element inside meaningful SVGs — it provides the accessible name. For decorative icons (a hamburger menu next to the word "Menu"), use aria-hidden="true". SVGO v4 preserves <title> by default. Do not strip it unless the icon is purely decorative and already hidden from assistive technology.

Sources

  • Penpot. "How to Optimize SVG Files: A Complete Guide for Beginners." September 5, 2025. penpot.app
  • Bushell, David. "SVG Optimization and Accessibility Basics." June 25, 2025. dbushell.com
  • Soueidan, Sara. "Useful SVGO[ptimization] Tools." January 26, 2015. sarasoueidan.com
  • SVGO. "Migration from v3 to v4." svgo.dev
  • SVGO. "preset-default Plugin Reference." svgo.dev
  • MDN Web Docs. "viewBox attribute." developer.mozilla.org
  • MDN Web Docs. "Content-Encoding." developer.mozilla.org
  • Joan Leon. "SVGs on the Web: Performance Comparison Based on How They Are Used." February 24, 2026. joanleon.dev
  • SVGOMG. "How to Optimize SVG Files." svgomg.net