SVG

Formats

SVG (Scalable Vector Graphics) is a text-based, XML vector image format for describing 2D graphics that scale cleanly at any resolution. Because it encodes shapes, paths, and text rather than pixels, SVG often delivers small transfer sizes for icons, logos, and diagrams, and can be styled with CSS, animated, and made accessible. As a text format, SVG benefits significantly from GZIP or Brotli compression and integrates well with modern build pipelines. It can be embedded inline in HTML for fine-grained control, or served as a separate, cacheable asset when reuse and caching are priorities.

Definition and scope

SVG is a W3C standard for describing vector graphics using XML. Instead of fixed pixels, it stores instructions for shapes, strokes, fills, gradients, and text. This makes it resolution-independent, scriptable, and highly compressible. Typical use cases include UI icons, logos, simple illustrations, charts, and diagrams where sharpness and scalability matter. Unlike raster formats (PNG, JPEG, WebP), SVG is best for geometry and text, not photographic detail.

SVG files can be embedded inline in HTML, referenced via <img>, used as CSS backgrounds, or injected through <object>, <iframe>, or <embed>. Inline placement exposes SVG to the DOM and CSS cascade, enabling theming, animations, and accessibility hooks. As external files, SVGs are cacheable and sharable across pages, which can reduce repeated transfer and improve long-term performance on multi-page visits.

Core features and syntax

Building blocks and structure

An SVG document uses a root <svg> element with attributes such as width, height, viewBox, and preserveAspectRatio. Common elements include <path>, <rect>, <circle>, <line>, and <text>, which can be grouped with <g>. Reusable content is defined with <defs>, <symbol>, and referenced via <use>. The viewBox defines the internal coordinate system, enabling responsive scaling independent of CSS layout dimensions.

Styling, animation, and interactivity

SVG supports presentation attributes (fill, stroke, stroke-width) and full CSS styling when embedded inline or linked with an internal stylesheet. Animations are possible via CSS transitions/animations or SVG SMIL (supported in modern browsers), and complex interactions can be added using JavaScript. Features like gradients, patterns, clipping, masking, and filters enable rich effects, though they can increase complexity and transfer size if overused.

Embedding modes and their implications

- Inline (<svg> in HTML): full CSS/JS control, easiest to make accessible, no extra request, but inflates HTML and reduces cache reuse.
- <img src>: simplest delivery and good caching; cannot target internal nodes with page CSS/JS; use the img’s alt for accessibility.
- CSS background-image: purely decorative; no semantic alt; respects CSS caching.
- <object>/<iframe>: isolates document context; can be styled internally; adds request overhead and sandboxing concerns.

Transfer size and compression

SVG is text, so HTTP content-encoding significantly reduces payload. GZIP commonly cuts size by 60–80%, and Brotli often outperforms GZIP at higher levels. Small icon SVGs routinely compress to a few hundred bytes, while complex illustrations can range from 5–50 KB compressed. Compared with PNG, SVG is typically smaller for simple shapes and larger for photo-like content or path-heavy exports from design tools with excessive precision and metadata.

Optimisation focuses on minification (removing whitespace, comments, unused IDs), flattening groups, simplifying paths, and reducing decimal precision. Tools like SVGO (and GUI wrappers) automate these transforms and can strip editor cruft. Delivery choices also affect performance: inlining avoids a request but bloats HTML and hinders caching; external SVGs enable long-lived caching and HTTP/2 multiplexing; sprites consolidate many icons into one request for improved reuse.

SEO and accessibility factors

Semantics, names, and labelling

When embedded with <img>, the alt attribute provides the accessible name. Inline SVGs can use role="img" with aria-labelledby pointing to <title> and optional <desc> elements for assistive technologies. Decorative graphics should be hidden with aria-hidden="true" or by omitting alt on purely decorative <img>. Text within SVG remains selectable and, when inline, may be indexable, but SVG is not a ranking signal by itself; it primarily supports usability and page quality signals tied to performance and accessibility.

Theming, contrast, and interaction states

Inline SVGs inherit CSS variables and media-query conditions (for example, prefers-color-scheme) to support dark mode and high-contrast themes. Focus, hover, and pressed states can be styled without swapping assets, which benefits both accessibility and performance. Care is needed to preserve sufficient colour contrast and hit targets, and to avoid relying solely on colour to convey meaning. For linked icons, ensure the focus ring is visible and pointer events behave as intended.

Security, sanitisation, and trust boundaries

SVGs can include scripts, external references, and <foreignObject>, which introduces XSS risk when handling untrusted input. Sanitise any user-supplied SVG server-side, strip scripting and event handlers, and serve with the correct Content-Type (image/svg+xml). Consider setting Content-Security-Policy to restrict inline scripts and external loads. For <img>-embedded SVG, most scripting is not executed, but sanitisation remains a prudent defence-in-depth step.

Use cases

- Brand marks and UI icons that must remain sharp across densities.
- Diagrams, charts, and infographics with selectable labels and accessible descriptions.
- Animated micro-interactions and stateful controls that benefit from CSS theming.
- Map overlays and schematic drawings where zooming is essential.
- Icon systems using SVG sprites to reduce requests and centralise theming.

SVG is poorly suited to photographic images, complex noise, or heavy blur/filter effects where raster formats (like WebP or AVIF) outperform in quality-to-size. For very intricate artwork exported from vector tools, consider simplifying geometry or rasterising layers that are visually static but path-heavy. In UI contexts, SVG avoids the need for multiple pixel-density variants and enables consistent rendering on high-DPI displays without extra assets.

Overview of browser support

All modern browsers support SVG in <img>, inline, and CSS backgrounds. Core features—paths, text, gradients, masks, and filters—are widely implemented. SMIL animation is supported in current versions of major browsers, though CSS animations are typically preferred for consistency with the rest of the page. The <foreignObject> element works across modern engines with some historical quirks on older iOS versions.

Styling limitations differ by embedding mode: SVG in <img> or CSS background cannot be styled from the parent page’s CSS; inline SVG can. CORS rules apply to cross-origin SVGs when referenced by <use> or when accessing SVG content via scripts. For compatibility, serve with correct MIME type, include a viewBox for responsiveness, and avoid deprecated xlink:href in favour of href on <use> where supported.

Implementation notes

Optimisation workflow and tooling

- Run SVGO (or similar) in CI to strip metadata, collapse groups, and limit precision (for example, 2–3 decimals).
- Remove hidden layers and editor-specific data before export.
- Prefer <symbol>/<use> sprites for shared icons; cache aggressively with far-future headers and content hashing.
- Benchmark inlining only for critical, above-the-fold icons to avoid bloating HTML; keep the rest external.

Responsive behaviour and layout control

- Always include a viewBox to enable scaling without distortion.
- For responsive inline SVG, omit width/height and control size via CSS; for <img>, set width/height attributes for intrinsic ratio and CLS prevention.
- Use preserveAspectRatio to enforce desired cropping/letterboxing behaviour.
- For CSS theming, rely on currentColor or CSS variables to align icon colours with text and themes.

Accessibility and semantics checklist

- Informative images: <img alt="…"> or inline role="img" with aria-labelledby to <title> (and optional <desc>).
- Decorative images: aria-hidden="true" or CSS backgrounds; avoid empty <title> as it may create noise.
- Maintain focus styles for interactive SVGs; ensure keyboard operability when SVG acts as a control.
- Test with screen readers to verify name and description exposure across embedding methods.

Security and delivery considerations

- Sanitise any untrusted SVG input; disable scripts and external references.
- Serve with Content-Type: image/svg+xml and enable GZIP/Brotli.
- Consider CSP directives (img-src, object-src, script-src) to constrain behaviour.
- For cross-origin sprites or <use> references, ensure proper CORS headers if required.

Comparisons

SVG vs raster formats (PNG, JPEG, WebP, AVIF)

- Strengths: Infinite scalability, crisp text/lines, CSS/JS styling, accessible structure, usually smaller for simple geometry.
- Trade-offs: Can be larger than modern rasters for photos; complex filters/paths can balloon size; rendering cost may rise with overly intricate DOMs.
- Typical approach: Use SVG for icons/logos/diagrams; use WebP/AVIF/JPEG for photos; reserve PNG for transparency-heavy rasters or when exact pixel fidelity is crucial.

SVG vs Canvas and icon fonts

- Canvas: bitmap drawing surface; great for dynamic, pixel-level updates and high-frequency animation; not inherently accessible or stylable after draw; snapshots pixels rather than DOM nodes.
- Icon fonts: lightweight and cacheable but limited semantics, kerning issues, and accessibility pitfalls; colour/shape limited without layering; SVG supersedes icon fonts in flexibility and accessibility.

FAQs

Is SVG always smaller than PNG or WebP?

No. SVG excels for simple shapes, icons, and text, often compressing to very small sizes. For photographic or highly detailed imagery, modern raster formats (WebP/AVIF/JPEG) usually deliver better size–quality trade-offs. Complex vector exports with many points, filters, or embedded raster images can exceed an equivalently legible PNG/WebP.

Should I inline SVGs or load them as external files?

Inline SVGs enable theming and reduce one request, which can help for a few critical icons above the fold. External files improve cache reuse across pages and keep HTML light. Many teams inline only critical UI icons and ship the rest as an external sprite or individual cacheable files to balance first-load performance with maintainability.

How do I make SVGs responsive and avoid layout shift (CLS)?

Include a viewBox to enable scaling, and for <img> provide width and height attributes to establish an intrinsic aspect ratio so the browser reserves space before the image loads. For inline SVG, control size with CSS while retaining the viewBox, and use preserveAspectRatio to prevent unintended stretching.

Can SVGs be animated efficiently for the web?

Yes. CSS and SMIL animations on SVG are widely supported and efficient for transforms, opacity, and simple property changes. Performance depends on complexity: animating many DOM nodes or filters can be expensive. Prefer transform and opacity changes, reduce node count, and test on low-end devices when shipping elaborate motion.

Are SVGs safe to use from third parties?

Treat untrusted SVG like untrusted HTML. Strip scripts, event handlers, and external references server-side, and serve with a restrictive Content-Security-Policy. When referencing third-party SVGs, consider hosting vetted copies or proxying through a sanitisation layer to minimise XSS risk and ensure consistent caching and compression.

Synonyms

Scalable Vector GraphicsSVG imageSVG fileVector SVGInline SVG