All articles
Formatters
24 min readBy Akash Bijwe

SVG Formatting: Read, Edit and Clean Vector Code

Learn how SVG is structured, how the viewBox and path data work, and how to format, edit and optimise SVG code for clean, accessible graphics.

SVG Formatting: Read, Edit and Clean Vector Code

SVG is one of the few image formats you can open in a text editor and understand. Logos, icons, charts, maps and illustrations on the modern web are often SVG, and every one of them is just code. That is a strength, because you can edit, animate and style it directly. It is also a weakness, because the SVG exported by design tools tends to be a dense, one-line wall of numbers. This guide explains how SVG is structured, how to format it so it is readable, how to edit it by hand, and how to clean it up before shipping.

What is SVG?

SVG, Scalable Vector Graphics, is an XML-based format for two-dimensional vector images. Instead of storing a grid of pixels, it stores shapes, paths, text and styling instructions. The browser draws those instructions at whatever size is needed, so the image stays sharp on a phone, a 4K monitor and a printed page.

SVG is standardised by the W3C. The current specification is SVG 2, and the MDN SVG documentation is the most practical reference for everyday use. Because SVG is an XML vocabulary, everything in our guide on XML formatting applies to it: one root element, matching tags, quoted attributes and escaped special characters.

A minimal SVG looks like this:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
  <circle cx="50" cy="50" r="40" fill="#2563eb" />
  <text x="50" y="56" text-anchor="middle" fill="#fff" font-size="20">SVG</text>
</svg>

The core building blocks

Learning a small set of elements lets you read almost any SVG.

  • <svg> is the root. It holds the namespace, the viewBox and optionally a width and height.
  • Basic shapes: <rect>, <circle>, <ellipse>, <line>, <polyline> and <polygon>.
  • <path> draws arbitrary shapes using the compact d attribute. Most icons are a single path.
  • <g> groups elements so you can transform or style them together.
  • <text> renders text.
  • <defs> holds reusable things that are not drawn directly, such as gradients, filters and clip paths.
  • <use> places a copy of an element defined elsewhere, which keeps repeated icons small.
  • <symbol> defines a reusable graphic, often used for icon sprites.
  • <title> and <desc> provide accessible names and descriptions.

Understanding the viewBox

The viewBox is the most important and most misunderstood attribute. It defines the internal coordinate system as four numbers: min-x min-y width height. In viewBox="0 0 100 100", the drawing space runs from 0 to 100 in both directions. The width and height attributes, or CSS, decide how large that space is displayed. The browser scales the coordinates to fit.

This is what makes SVG scalable. If you remove the viewBox, the graphic can no longer scale properly, and it is one of the most common reasons an icon displays at the wrong size or gets cropped.

Reading path data

The d attribute of a <path> is a mini-language. Each letter is a command, followed by numbers:

Command Meaning
M x y Move to a point without drawing
L x y Draw a line to a point
H x / V y Horizontal or vertical line
C x1 y1 x2 y2 x y Cubic Bezier curve
Q x1 y1 x y Quadratic Bezier curve
A rx ry rot large sweep x y Elliptical arc
Z Close the path

Uppercase commands use absolute coordinates, and lowercase commands use coordinates relative to the current point. Formatted and spaced out, a path becomes readable:

<path d="M 10 10
         L 90 10
         L 90 90
         L 10 90
         Z" />

Why SVG formatting matters

Design tools and export pipelines often produce SVG like this:

<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"><g fill="none"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/></g></svg>

It works perfectly, but it is difficult to work with. Formatting helps in four ways:

  • Readability. Indentation shows the grouping, so you can tell which shapes belong together.
  • Editing. To change a colour, add an id or adjust a stroke width, you first need to find the right element.
  • Reviewing and diffing. One element per line turns an unreadable change into a clear one. Teams that store icons in a repository benefit from this.
  • Debugging. Missing viewBox values, stray transforms and duplicate IDs are easy to spot in a formatted file.

Because SVG is XML, formatting only changes whitespace between elements. Take care inside <text> and <tspan> elements, where whitespace can be significant and a reflow can change the rendered spacing.

Real-world use cases

Cleaning up exports. Files from Figma, Illustrator, Inkscape and Sketch often include editor metadata, default attributes, comments and verbose IDs. Formatting reveals what is in there.

Restyling icons with CSS. Inline SVG can be styled with CSS. Setting fill="currentColor" lets an icon inherit the text colour, which makes theming and dark mode simple.

Animation. SVG elements can be animated with CSS, SMIL or JavaScript. Readable markup is essential when you need to target a particular path or group.

Icon systems. Many sites combine icons into a sprite of <symbol> elements and reference them with <use>.

Accessibility fixes. Adding role="img", a <title> and aria-labelledby makes a meaningful graphic understandable to screen readers.

Converting to components. Frameworks such as React need SVG attributes converted to camelCase, such as stroke-width to strokeWidth. The DevUtilX SVG to JSX tool handles this.

Common mistakes

  • Missing viewBox. The graphic will not scale, and may be cropped or too small.
  • Missing namespace. A standalone .svg file needs xmlns="http://www.w3.org/2000/svg". Inline SVG inside HTML does not.
  • Fixed width and height on everything. This stops the graphic being responsive. Prefer a viewBox and let CSS control size.
  • Duplicate IDs. When you inline several SVGs on one page, gradients and clip paths with the same id collide, and the wrong one can be used.
  • Hard-coded colours. Literal fill="#000" cannot respond to themes. Use currentColor or CSS variables where appropriate.
  • Unoptimised exports. Too many decimal places, redundant groups and embedded editor data inflate file size.
  • Embedding untrusted SVG. SVG can contain <script> and event handler attributes. Never inline SVG from an untrusted source without sanitising it. Loading SVG through an <img> tag disables scripts, but inline use does not.

Step-by-step: format SVG with DevUtilX

For a quick clean-up with no installation, use the DevUtilX SVG Formatter, which runs in your browser.

  1. Open the SVG formatter tool.
  2. Paste your SVG code into the input editor.
  3. Choose your indentation.
  4. Run the formatter and review the indented structure.
  5. Copy the result back into your project.

Your code is processed locally and is not uploaded. After formatting, make your edits by hand: rename IDs, replace fixed colours with currentColor, add a <title>, or delete unneeded attributes. When the file is ready for production, run it through the SVG Optimizer or the SVG Minifier to reduce its size.

Editing SVG by hand: a short workflow

  1. Format first. You cannot edit what you cannot read.
  2. Check the root. Confirm the xmlns, viewBox and any fixed width or height.
  3. Remove noise. Delete editor comments, metadata, empty groups and unused <defs>.
  4. Simplify styling. Move repeated inline styles into attributes or a stylesheet, and use currentColor for icons that should follow text colour.
  5. Add accessibility. Give meaningful graphics a <title>, and hide decorative ones with aria-hidden="true".
  6. Test at several sizes and against light and dark backgrounds.
  7. Optimise last. Minify and compress only when editing is finished.

Optimising SVG for production

Formatted source is for people. Production files should be small. The standard tool is SVGO, a Node.js optimiser that removes metadata, collapses groups, shortens path data and rounds numbers. A typical configuration keeps the viewBox:

// svgo.config.js
module.exports = {
  plugins: [
    {
      name: "preset-default",
      params: { overrides: { removeViewBox: false } },
    },
  ],
};

Keeping the viewBox matters, as described above. After optimisation, serving the file with gzip or Brotli compression typically shrinks it further, since SVG is text.

Also consider how the SVG is delivered:

Method Styleable with CSS Cached separately Notes
Inline in HTML Yes No Best for icons you restyle or animate
<img src="a.svg"> No Yes Simple; scripts are disabled
CSS background-image No Yes Good for decoration
<use href="sprite.svg#id"> Partly Yes Efficient for icon sets

Best practices

  • Always keep a viewBox, and let CSS control the size.
  • Format source files and store them readable in version control.
  • Minify and optimise in the build, not by hand.
  • Use currentColor for icons that should match surrounding text.
  • Prefer unique, descriptive IDs, or strip unneeded IDs entirely.
  • Provide text alternatives for informative graphics.
  • Sanitise any SVG that comes from users before inlining it.
  • Round numbers sensibly. Two or three decimals are usually enough for icons.
  • Do not use SVG for photographs. Raster formats such as WebP or AVIF are far better for photographic images.

Comparison: SVG and other image formats

Format Type Best for Limitation
SVG Vector Icons, logos, charts, illustrations Poor for photos; complex scenes get large
PNG Raster Screenshots, images needing transparency Fixed resolution
JPEG Raster Photographs No transparency, lossy
WebP / AVIF Raster Photos and graphics at small sizes Needs fallbacks in older browsers

Choose SVG when the image is made of shapes and needs to scale or be styled. Choose a raster format when the image is a photograph.

How a browser turns SVG into pixels

Knowing what the browser does with your markup explains most formatting and editing decisions. The process has four steps.

First, the parser reads the file as XML (for a standalone .svg) or through the HTML parser (for inline SVG). Second, the browser builds a DOM tree. Every <path> and <g> becomes a real node you can query with document.querySelector. Third, CSS is matched against that tree, so a rule such as .icon path { stroke: currentColor } works just as it does for HTML. Finally, the renderer walks the tree in document order and paints each shape.

That last point matters. SVG has no z-index for ordinary shapes. Elements that appear later in the file paint on top of earlier ones. When you reorder lines in a formatted file, you change the stacking order, not just the layout of the source. Treat reordering as an edit that needs a visual check.

Coordinates, units and preserveAspectRatio

Inside the viewBox, coordinates are unitless "user units". One user unit equals one CSS pixel until the browser scales the viewBox to fit the element's box. A viewBox="0 0 24 24" icon displayed in a 48 by 48 pixel box simply draws everything at double size.

What happens when the viewBox and the element box have different aspect ratios? The preserveAspectRatio attribute decides. Its default, xMidYMid meet, scales the artwork uniformly until it fits entirely inside the box, then centres it. That is why a square icon placed in a wide box shows empty space on the sides instead of stretching. The value slice fills the box and crops the overflow. The value none stretches the artwork non-uniformly, which is almost never what you want for icons but is useful for decorative backgrounds such as wave dividers.

Nested coordinate systems

Every transform creates a new coordinate system for the element and its children. A group with transform="translate(10 20) scale(2)" moves the origin, then doubles all lengths inside it, including stroke widths. Transforms apply right to left in terms of the effect on a point, which surprises many people: in translate(10 20) scale(2), a point is scaled first and then translated.

Design tools love to wrap everything in several nested groups with transforms. Flattening them is one of the best clean-ups, and it is also the riskiest, because stroke widths and gradient directions change along with the geometry. Optimisers handle the simple cases. For anything unusual, flatten by hand and compare the render before and after.

Path data in depth

The path table above lists the main commands. Real exported paths use several shortcuts that make them hard to read until you know the rules.

Shorthand curves

The S command draws a cubic curve whose first control point is the reflection of the previous curve's second control point. T does the same for quadratic curves. They save numbers and keep joins smooth. When you move a point in the middle of a path that uses S, the reflected control point moves with it, so hand-editing these paths can bend more than you expect. If you need precise control, rewrite S as an explicit C first.

Implicit repetition

After a command letter you can supply more than one set of arguments, and the browser repeats the command. L 10 10 20 20 30 30 draws three line segments. After M, extra coordinate pairs are treated as L, and after lowercase m they become l. So M 0 0 10 10 means "move to the origin, then draw a line to (10, 10)".

Compact number syntax

The path grammar lets you drop separators wherever the number boundaries are unambiguous. A minus sign starts a new number, and so does a second decimal point. These two paths are identical:

<path d="M10 -5.5 L0.5 0.5" />
<path d="M10-5.5L.5.5" />

The second form is what optimisers produce. It is valid and renders the same, but it is very hard to read, which is the main reason to keep a formatted, unminified copy of the source.

Arc flags

The arc command A rx ry rot large sweep x y has two flag arguments, each a single 0 or 1. They pick which of the four possible arcs between two points is drawn. The large flag chooses the arc greater than 180 degrees when set. The sweep flag chooses the drawing direction: 1 means clockwise in the usual screen coordinate system, where y grows downward. Because flags are always a single character, minified paths may write them without spaces, as in a1 1 0 011 1. Here 0, 1 and 1 are the rotation, the flags and the start of the coordinate. Not every tool parses that form correctly, which is one reason to test minified icons in more than one renderer.

Styling: attributes, CSS and inheritance

SVG lets you set appearance in three places. You can use a presentation attribute such as fill="red", an inline style="fill: red", or a CSS rule in a stylesheet or <style> element. They are not equal.

Presentation attributes have the lowest priority of the three. Any CSS rule, even one with very low specificity, overrides them. That is useful: you can ship an icon with fill="currentColor" and recolour it from the page without touching the file. It also means a stray <style> block exported by a design tool can silently override attributes you edit by hand. When a colour change "does nothing", search the file for a <style> element and for class attributes first.

Making icons themeable

Three techniques cover almost every theming need.

  1. currentColor. The icon takes the CSS color of its parent. Use it for single-colour icons.
  2. CSS custom properties. Write fill="var(--icon-accent, #2563eb)" or use a style attribute with the same value. The fallback keeps the icon correct where the property is undefined. Custom properties inherit, so they also reach content referenced through <use>.
  3. Dark-mode media queries inside the SVG. A standalone SVG can include @media (prefers-color-scheme: dark) in its own <style> block. When loaded through <img>, the SVG responds to the user's system preference, since it cannot see the page's CSS. This suits logos that must work as images.

For more on structuring stylesheets so these choices stay maintainable, see our guide to CSS formatting and architecture.

Worked example: cleaning a real export

Here is a typical export, trimmed for space. It carries an XML declaration, editor metadata, a generator comment and verbose attributes:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Generator: ExampleEditor 1.0 -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:editor="http://example.com/ns/editor" width="48px" height="48px" viewBox="0 0 48 48" version="1.1" editor:version="1.0.4"><metadata>exported with ExampleEditor</metadata><g id="Layer_1" fill="none" fill-rule="evenodd" stroke="#000000" stroke-width="2.000000" stroke-linecap="round"><g transform="translate(0.000000, 0.000000)"><path id="Path" d="M 24.000000 6.000000 L 24.000000 42.000000 M 6.000000 24.000000 L 42.000000 24.000000"/></g></g></svg>

The cleanup goes in a fixed order. Start by formatting so the structure is visible. Then work through these decisions.

  • Delete the XML declaration and comment for inline use. Keep the declaration only for standalone files where you need an explicit encoding.
  • Remove the editor namespace, its attribute and the <metadata> block. They are inert for rendering.
  • Drop px from width and height, or remove both and let CSS size the icon, since the viewBox is present.
  • Delete the identity transform. translate(0, 0) does nothing, and removing it lets the redundant group go too.
  • Trim number precision. 2.000000 is just 2, and 24.000000 is 24.
  • Replace the hard-coded black stroke with currentColor.
  • Remove the generic id values that only describe layers, such as Layer_1 and Path, because they invite collisions when several exports share a page.

After formatting and cleaning, the same icon reads like this:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48"
     fill="none" stroke="currentColor" stroke-width="2"
     stroke-linecap="round" aria-hidden="true">
  <path d="M24 6v36M6 24h36" />
</svg>

Notice the final path. Absolute L commands became relative v and h commands, which also collapsed two sub-paths into one short string. The picture is a plus sign, and the source now says so. The fill-rule attribute went away because the path has no fill to evaluate.

Formatting conventions that keep diffs clean

The generic rules from our XML formatting guide apply, but SVG benefits from a few extra conventions.

Indent by two spaces and put each element on its own line. Two spaces keeps deeply nested charts from running off the screen.

Break long attribute lists. When a tag exceeds your line limit, put one attribute per line, aligned under the first. Reviewers can then see exactly which attribute changed.

Order attributes consistently. A common pattern is identity first (id, class), then geometry (x, y, width, height, d), then appearance (fill, stroke), then accessibility attributes. Consistency matters more than the particular order.

Wrap long path data on command boundaries. Start each command letter on a new line inside the d attribute, as in the earlier example. Diffs then show which segment changed. Whitespace in path data is insignificant, so this is safe.

Never reflow text content. In <text> and <tspan>, a formatter that adds line breaks and indentation can introduce visible gaps, because the default whitespace handling collapses runs of spaces but still keeps single spaces between inline pieces. If an element needs exact spacing, keep it on one line or set xml:space="preserve" deliberately.

Keep one SVG per file in source control, named for what it shows, such as icon-search.svg. When you review changes, a diff of two SVG files is only useful if both sides are formatted the same way.

Building an icon sprite

A sprite puts many icons in one file as <symbol> elements. Pages reference them by id. Each symbol carries its own viewBox, so every instance scales correctly.

<!-- icons.svg -->
<svg xmlns="http://www.w3.org/2000/svg">
  <symbol id="icon-plus" viewBox="0 0 48 48">
    <path d="M24 6v36M6 24h36" fill="none" stroke="currentColor"
          stroke-width="2" stroke-linecap="round" />
  </symbol>
  <symbol id="icon-minus" viewBox="0 0 48 48">
    <path d="M6 24h36" fill="none" stroke="currentColor"
          stroke-width="2" stroke-linecap="round" />
  </symbol>
</svg>
<svg class="icon" width="24" height="24" aria-hidden="true">
  <use href="/assets/icons.svg#icon-plus" />
</svg>

Three details trip people up. First, an external sprite must be served from the same origin as the page, because browsers apply same-origin rules to <use> references to external files. Second, the href attribute is the modern form. Older code uses xlink:href, which still works but needs the xlink namespace declared in standalone files. Third, you cannot style the internals of a <use> instance with ordinary selectors, because the referenced content lives in a closed shadow tree. Only inherited properties cross that boundary, which is why currentColor and custom properties are the right tools for sprites.

If you inline the sprite in the page instead, hide it with width="0" height="0" and style="position: absolute" rather than display: none. Some browsers do not resolve gradients or clip paths inside a subtree that is not rendered.

Accessibility in more detail

A graphic needs either a text alternative or an explicit marker saying it is decoration. There is no useful middle ground.

Informative graphics. Give the root role="img" and a <title> as its first child. Link them with aria-labelledby so assistive technology reads the title reliably:

<svg role="img" aria-labelledby="chart-title chart-desc" viewBox="0 0 200 100">
  <title id="chart-title">Monthly signups</title>
  <desc id="chart-desc">Bar chart showing signups rising each month from January to June.</desc>
  <!-- bars -->
</svg>

Keep the title short, like an image alt attribute. Use <desc> for the longer explanation that a chart needs.

Decorative graphics. Use aria-hidden="true" and add focusable="false" for good measure. An icon next to a visible text label is decorative, because the label already carries the meaning.

Icon-only buttons. Put the accessible name on the <button>, not the SVG. Use aria-label or visually hidden text, and mark the icon itself as hidden. Otherwise a screen reader may announce the button twice or not at all.

Contrast and motion. Strokes and fills that convey meaning should meet the same contrast ratios as text and UI components. If you animate, respect @media (prefers-reduced-motion: reduce) and turn the motion off or cut it down.

Animating SVG safely

CSS handles most animation. A classic example is the line-drawing effect, which uses stroke-dasharray and stroke-dashoffset:

.draw {
  stroke-dasharray: 1;
  stroke-dashoffset: 1;
  animation: draw 1.2s ease forwards;
}
@keyframes draw {
  to { stroke-dashoffset: 0; }
}
@media (prefers-reduced-motion: reduce) {
  .draw { animation: none; stroke-dashoffset: 0; }
}

For the unit values to work, the path needs pathLength="1" on the element. That attribute tells the browser to treat the path as one unit long, whatever its true length, so you do not have to measure it with JavaScript.

Readable markup helps here. You need stable class names or ids on the exact paths you animate, and an optimiser may delete ids it considers unused. Check your optimiser's cleanupIds behaviour, and exclude the ids your CSS or scripts rely on.

SMIL animation (<animate>, <animateTransform>) is part of SVG and works in current browsers without scripts. It only runs when the SVG is inline or loaded as an image, and it is harder to pause or respect for reduced motion. Prefer CSS for anything interactive.

Security considerations

An SVG file is a document that can run code. That makes it different from PNG or JPEG, and it is the reason the existing advice to sanitise uploads matters.

What can go wrong:

  • Scripts. A <script> element or an attribute such as onload or onclick executes in the page when the SVG is inline, and in the SVG's own origin when someone opens the file directly.
  • <foreignObject>. It embeds HTML inside SVG, which opens the door to HTML-based injection.
  • External references. Links to remote images, stylesheets or fonts leak the viewer's IP address and can track opens.
  • javascript: URLs in href values on links and <use>.
  • Resource exhaustion. Deeply nested groups, huge filters and recursive references can freeze a tab.

How to defend:

  1. Prefer <img> for untrusted files. An SVG loaded as an image runs no scripts and loads no external resources.
  2. If you must inline user SVG, sanitise it with a maintained library that has an SVG profile, and use an allow-list of elements and attributes rather than a block-list. Test the result with known hostile samples.
  3. Serve uploads from a separate origin (a cookie-less domain or a storage bucket domain) so that a file opened directly cannot reach your session.
  4. Set the correct Content-Type, which is image/svg+xml, and add X-Content-Type-Options: nosniff.
  5. Add a Content Security Policy that blocks inline scripts on pages that display SVG.
  6. Validate size and complexity at upload time, and reject files above a sensible limit.

Remember that optimisers are not sanitisers. SVGO has a plugin for removing scripts, but it exists to shrink files. Treat it as a convenience for your own assets, never as a security boundary.

Performance and memory

SVG is cheap when it is small and costly when it is not. Three things drive the cost.

Node count. Every element is a DOM node that the browser must style, lay out and paint. A map with tens of thousands of tiny paths will be slow to parse and slow to repaint, however few kilobytes it occupies on disk. If you only need to show such a graphic, a raster image or canvas may serve better. If you need interactivity, simplify paths, merge shapes that share a style, and drop invisible details at small sizes.

Expensive effects. Blur, drop-shadow and displacement filters are computed per pixel and re-run when the element changes. Apply them to small areas, avoid animating them, and prefer a pre-rendered raster for large soft shadows.

Path precision. Extra decimals cost bytes and add nothing visible. For a 24 by 24 icon, two decimals are well below what a screen can display. For a large illustration with a viewBox thousands of units wide, one decimal or even integers may suffice. Choose precision relative to the viewBox size, not as a global habit.

Delivery adds its own trade-offs. Inline SVG avoids a network request but cannot be cached on its own, so a large inline graphic repeated across pages is re-downloaded with every HTML response. External files cache well but cost a request and cannot be styled from the page. A sprite balances the two for icon sets. Our SVG and XML minification guide covers the size side in more depth.

Tooling: editors, linters and the command line

You can build a formatting workflow from small, standard pieces.

Editors. Most editors treat .svg as XML and can fold, indent and validate it, and many show an inline preview. Set the file type to XML or SVG, configure two-space indentation, and enable format-on-save only if your formatter is known to leave text content alone.

Command line. xmllint --format file.svg from libxml2 re-indents any well-formed XML. SVGO can also pretty-print its output when you ask for it:

// svgo.config.js, for source files that humans will edit
module.exports = {
  multipass: true,
  js2svg: { pretty: true, indent: 2 },
  plugins: [
    {
      name: "preset-default",
      params: { overrides: { removeViewBox: false } },
    },
  ],
};

This keeps the clean-up benefits and the readable layout. Use a second, non-pretty configuration for the production build.

A small audit script. Even without a framework you can catch the most common mistakes in CI. This Node script checks for a missing viewBox, a missing namespace, scripts, event handlers and duplicate ids:

// audit-svg.mjs
import { readFileSync } from "node:fs";

const svg = readFileSync(process.argv[2], "utf8");
const ids = [...svg.matchAll(/\sid="([^"]+)"/g)].map((m) => m[1]);
const dupes = ids.filter((id, i) => ids.indexOf(id) !== i);
const problems = [];

if (!/<svg[^>]*\sviewBox="/.test(svg)) problems.push("missing viewBox");
if (!/<svg[^>]*\sxmlns="http:\/\/www\.w3\.org\/2000\/svg"/.test(svg))
  problems.push("missing xmlns");
if (/<script[\s>]/i.test(svg)) problems.push("contains <script>");
if (/\son[a-z]+\s*=/i.test(svg)) problems.push("contains event handler");
if (dupes.length) problems.push("duplicate ids: " + [...new Set(dupes)].join(", "));

console.log(problems.length ? problems.join("\n") : "ok");
process.exitCode = problems.length ? 1 : 0;

Run it with node audit-svg.mjs icon.svg. A non-zero exit code fails the check. Regular expressions are a blunt instrument, so treat the script as a tripwire and not as a parser. For stricter checks, parse the file with an XML library.

Pre-commit and CI. Run the audit on staged .svg files in a pre-commit hook, and run the same script across the whole icon folder in CI. Add an optimiser step in the build so that production output never depends on someone remembering to run it.

Troubleshooting guide

When an SVG misbehaves, find the symptom below and work through the likely causes in order.

Symptom Likely cause Fix
Image is blank Missing xmlns in a standalone file, or fill and stroke both none Add the namespace; check appearance attributes
Icon is cropped viewBox does not cover the artwork Set the viewBox to the real bounds
Icon is the wrong size Missing viewBox, or fixed width and height Add a viewBox; size it with CSS
Colour will not change A <style> block or inline style overrides your attribute Search for <style> and class; use currentColor
Wrong gradient appears Duplicate ids across inlined SVGs Make ids unique or prefix them per file
Stroke looks too thick after resizing A transform scaled the group Use vector-effect="non-scaling-stroke" or fix the transform
Sprite icon does not render Cross-origin sprite, or wrong fragment id Serve from the same origin; check the id
Text looks different after formatting Whitespace changed inside <text> Restore the original spacing
File fails to open with "XML parsing error" Unescaped & or <, or unclosed tag Validate as XML; escape special characters
Looks fine in the browser, wrong in another tool Unsupported feature such as CSS in <style> or foreignObject Convert styles to attributes; test in the target tool

Two habits speed up diagnosis. Open the browser's developer tools and inspect the element, because the computed styles panel shows which rule won. And bisect: delete half the file, check the result, and repeat until the faulty element is isolated.

Moving SVG into a framework

The SVG to JSX tool covers the mechanical conversion. Know what it changes so you can review the result.

  • Attribute names become camelCase: stroke-width to strokeWidth, fill-rule to fillRule, class to className.
  • Namespaced attributes such as xlink:href become xlinkHref, though plain href is preferred today.
  • The style attribute changes from a CSS string to an object, so style="fill:red" becomes style={{ fill: "red" }}.
  • Self-closing tags are required for empty elements.
  • Ids stay global to the document. Two components that each define id="grad" will collide, so generate ids per instance or avoid ids entirely.

After conversion, replace fixed width and height with props, pass ...props to the root so callers can add classes and aria attributes, and keep currentColor as the default colour. Build tools also offer loaders that import .svg files as components, which keeps the source files formatted and the conversion automatic.

A team checklist

Agree on a short list and put it in your contributing guide. A workable version:

  1. Every SVG in the repo is formatted with two-space indentation and one element per line.
  2. Every file has an xmlns (standalone) and a viewBox.
  3. Icons use currentColor and have no hard-coded brand colours unless they are logos.
  4. No <script>, event handlers, foreignObject or external references in source files.
  5. Meaningful graphics have a <title>. Decorative ones have aria-hidden="true".
  6. Ids are unique across the page, or removed.
  7. The build optimises everything, and the CI audit passes.
  8. Reviewers check a rendered preview, not just the markup diff.

Case study: untangling an icon library

Consider a team that inherits a folder of icons exported by three designers over several years. Some have a fixed colour, some use <style> blocks with generic class names like cls-1, and some use identical ids for their gradients.

Reading the files is the first hurdle, so the team formats everything with one configuration and commits that as a single "formatting only" change. Later changes then produce small, meaningful diffs. Next they run the audit script and fix the findings in order: missing viewBoxes first, then duplicate ids, then colours. The class names inside <style> blocks are the hardest to untangle, because two icons that both define .cls-1 clash when inlined on the same page. The team moves styling into attributes using currentColor, which removes the blocks entirely.

Finally they build a sprite, switch the site to <use>, and add the CI check. Nothing about the process was clever. It worked because they formatted first, changed one kind of problem at a time, and automated the checks.

FAQ

Is SVG just XML?
Yes. SVG is an XML vocabulary, so it must be well-formed, with one root and properly closed tags. That is why XML tools can format and validate it.

Why does my SVG show at the wrong size or get cut off?
Usually the viewBox is missing or does not match the drawing's coordinates. Set it to the real extent of the artwork, and control display size with CSS.

Can I style SVG with CSS?
Yes, when it is inline in the HTML, or when you use <use> with suitable custom properties. An SVG loaded through <img> cannot be styled from the page.

Does formatting change how an SVG looks?
Not normally. It only changes whitespace between elements. Be careful inside text elements, where whitespace can affect spacing.

Is SVG safe to use?
SVG you create yourself is fine. Because SVG can contain scripts, treat uploads from users as untrusted and sanitise or serve them safely.

Should I minify or format SVG?
Both, at different stages. Keep formatted files in your repository for editing, and minify or optimise them in the build for delivery.

Why does my icon stay black when I set a CSS colour?
The SVG probably has a hard-coded fill or stroke, or a <style> rule that overrides your CSS. Replace the fixed colour with currentColor and remove the conflicting rule.

Should I use xlink:href or href on <use>?
Use plain href. It works in current browsers. Only legacy environments need xlink:href.

Can I use an external sprite from a CDN?
Not directly with <use>, because external references must be same-origin. Serve the sprite from your own domain, or inline it.

What is the difference between <symbol> and <g> in a sprite?
A <symbol> is never drawn on its own and can carry its own viewBox, so each instance scales independently. A <g> is drawn wherever it appears and has no viewBox.

Is it safe to optimise an SVG repeatedly?
Generally yes, since the output of an optimiser is valid SVG. Optimisation can remove ids or attributes your CSS and scripts depend on, so configure those exceptions and compare the render.

Conclusion

SVG is code you can read, edit and style, once it is formatted. Learn the handful of core elements and the viewBox, clean up exports before committing them, use currentColor and good accessibility attributes, and optimise only at the end. For a quick clean-up of any graphic, try the SVG Formatter. To keep going, read our guides on XML formatting and HTML formatting.

Further reading

Try the tools

Further reading

Related articles