All articles
Formatters
7 min readBy DevUtilX Team

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.

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.

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