Skip to content

Lesson 10 of 52HTML

SVG for the Web

Read and write SVG: viewBox, path commands, four ways to embed icons, currentColor theming, accessible icons, line-drawing animation, SVGO and safe uploads.

26 min read0/4 questions

Your designer exports forty icons from Figma and drops them in the repo. Each file is 4 KB, mostly editor metadata. Half of them stay black when the site switches to dark mode, one is blurry at 2x zoom because it was really a PNG, and a screen reader announces "image, image, image" all the way along the toolbar. None of that is the designer's fault: it is what happens when nobody on the team understands SVG. SVG (Scalable Vector Graphics) is the format for icons, logos, diagrams and simple charts on the web, and it is code you can read and change. This lesson teaches you to read it, embed it the right way for each job, theme it, make it accessible, animate it, shrink it, and stop it from becoming a security hole.

The coordinate system: viewBox versus width and height

An SVG has two separate sizes, and mixing them up causes most SVG confusion.

  • viewBox="minX minY width height" defines the drawing's own coordinate system: the canvas the shapes are drawn on. viewBox="0 0 24 24" means "my drawing lives in a 24 by 24 unit square starting at 0,0".
  • width and height (attributes or CSS) set how big the SVG is on the page, in CSS pixels.

The browser maps the viewBox onto the box you give it. A 24-unit icon shown at 96px is scaled 4x, and because shapes are maths rather than pixels, it stays crisp. That is why one SVG serves every screen density, where a PNG needs 1x, 2x and 3x files.

HTML & CSS
<style> svg { border: 1px dashed #999; vertical-align: middle; margin-right: 8px; }</style><p>The same 24 by 24 drawing at three sizes:</p><svg viewBox="0 0 24 24" width="24" height="24"><circle cx="12" cy="12" r="9" fill="none" stroke="black" stroke-width="2"/><path d="M8 12l3 3 5-6" fill="none" stroke="black" stroke-width="2"/></svg><svg viewBox="0 0 24 24" width="48" height="48"><circle cx="12" cy="12" r="9" fill="none" stroke="black" stroke-width="2"/><path d="M8 12l3 3 5-6" fill="none" stroke="black" stroke-width="2"/></svg><svg viewBox="0 0 24 24" width="96" height="96"><circle cx="12" cy="12" r="9" fill="none" stroke="black" stroke-width="2"/><path d="M8 12l3 3 5-6" fill="none" stroke="black" stroke-width="2"/></svg><p>A box with a different shape: preserveAspectRatio decides what happens.</p><svg viewBox="0 0 24 24" width="160" height="60"><circle cx="12" cy="12" r="9" fill="gold"/></svg><svg viewBox="0 0 24 24" width="160" height="60" preserveAspectRatio="xMinYMid meet"><circle cx="12" cy="12" r="9" fill="gold"/></svg><svg viewBox="0 0 24 24" width="160" height="60" preserveAspectRatio="none"><circle cx="12" cy="12" r="9" fill="gold"/></svg>

Preview

When the box and the viewBox have different shapes, preserveAspectRatio decides. The default, xMidYMid meet, scales the drawing to fit and centres it, like object-fit: contain. slice fills the box and crops, like cover. none stretches, which is right for a decorative wave or a chart background that must fill its container, and wrong for everything else. Try changing the viewBox of the first icon to 0 0 12 12: you are now looking at only its top-left quarter, zoomed in. The viewBox is a camera.

One more detail: an inline SVG is an inline element, so it sits on the text baseline and leaves a few pixels of gap below it, just like an img. Set display: block or vertical-align: middle when that gap bites.

Shapes and the path mini-language

SVG has simple shapes (rect, circle, ellipse, line, polyline, polygon), but almost every real icon is made of path elements. A path's d attribute is a tiny drawing language: a letter is a command, numbers are its arguments. Uppercase means absolute coordinates in viewBox units. Lowercase means relative to where the pen currently is.

CommandMeaningArguments
M / mMove the pen without drawingx y
L / lLine tox y
H / h, V / vHorizontal or vertical linex, or y
C / cCubic Bezier curvetwo control points, then the end point
Q / qQuadratic Bezier curveone control point, then the end point
A / aElliptical arcrx ry rotation large-arc sweep x y
Z / zClose the shape back to its startnone

Here is a home icon in the style of the open source Lucide set, taken apart. Edit the numbers and watch the shape change.

HTML & CSS
<svg viewBox="0 0 24 24" width="200" height="200" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <!-- the house outline: start at 3,10, up to the roof peak, down, along the floor --> <path d="M3 10 L12 3 L21 10 V20 a1 1 0 0 1 -1 1 H4 a1 1 0 0 1 -1 -1 Z"/> <!-- the door: move, go up 6, across 6, down 6 --> <path d="M9 21 v-6 h6 v6"/></svg>

Preview

Read the first path aloud: move to (3,10), line to the roof peak at (12,3), line down to (21,10), vertical line to y=20, a tiny relative arc for the rounded corner, horizontal line back to x=4, another corner, then close. The door uses only relative commands, which is why it reads as "up 6, right 6, down 6". You will rarely write paths by hand, but being able to read one lets you fix a misaligned icon, trim a stray point, or spot that an "SVG" is just a base64 PNG wrapped in an <image> tag.

Predict the outputHTML

The viewBox is 0 0 24 24. Where is the pen (x,y) at the end of this path, just before Z?

<path d="M2 2 L10 2 l0 8 h-4 Z"/>
Need a nudge? Hints walk you through it.

Stroke, fill and keeping lines even

fill paints the inside of a shape, stroke paints its outline. Line icons use fill="none" and a stroke. Solid icons use a fill and no stroke. Three stroke properties shape the look:

  • stroke-width is in viewBox units, so it scales with the icon. A 2-unit stroke on a 24-unit icon is 2px at 24px and 4px at 48px.
  • stroke-linecap (butt, round, square) shapes open line ends.
  • stroke-linejoin (miter, round, bevel) shapes corners.

Scaling strokes is what you want for icons. For a chart or a diagram that stretches with preserveAspectRatio="none", it is not: the lines get fat in one direction. vector-effect: non-scaling-stroke keeps the stroke at its CSS pixel width whatever the scale.

HTML & CSS
<style> svg { width: 100%; height: 80px; border: 1px solid #ddd; display: block; margin-bottom: 8px; } .fixed path { vector-effect: non-scaling-stroke; }</style><p>Stretched sparkline, scaling stroke:</p><svg viewBox="0 0 100 20" preserveAspectRatio="none"><path d="M0 15 L20 10 L40 12 L60 4 L80 8 L100 2" fill="none" stroke="crimson" stroke-width="2"/></svg><p>Same path with non-scaling-stroke:</p><svg class="fixed" viewBox="0 0 100 20" preserveAspectRatio="none"><path d="M0 15 L20 10 L40 12 L60 4 L80 8 L100 2" fill="none" stroke="crimson" stroke-width="2"/></svg>

Preview

Four ways to put SVG on a page

The same file can reach the page four ways, and each has a different set of powers.

MethodStyleable with page CSSCached as a fileScript runsBest for
Inline <svg> in the HTMLYes, fullyNo, part of the HTMLYes (it is your DOM)Icons that change colour, interactive charts
<img src="logo.svg">NoYesNoLogos, illustrations, anything you do not need to restyle
CSS background-image or mask-imageColour only, via the mask trickYesNoDecorative icons in CSS, tinting one file many colours
Sprite: <symbol> + <use href="#id">Yes, through currentColor and custom propertiesInline sprite: no. External same-origin file: yesInline: yesMany icons repeated across a page

Inline SVG is the most powerful and the most common for UI icons, but every inline icon is DOM nodes in every page's HTML. Forty icons repeated across a 200-row table is thousands of extra nodes, which slows parsing, styling and layout. A sprite defines each icon once as a <symbol> and stamps out copies with <use>, which keeps the HTML small. The mask-image trick turns any SVG file into a single-colour shape you paint with background-color.

HTML & CSS
<style> .row { display: flex; gap: 16px; align-items: center; margin-bottom: 12px; } .icon { width: 32px; height: 32px; } /* mask trick: the SVG is a stencil, background-color is the paint */ .masked { width: 32px; height: 32px; background-color: teal; mask: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><path d='M12 2l3 7h7l-5.5 4.5 2 7.5-6.5-4.5-6.5 4.5 2-7.5L2 9h7z'/></svg>") center / contain no-repeat; } .masked.alt { background-color: darkorange; }</style> <!-- one sprite, defined once, hidden --><svg width="0" height="0" style="position: absolute" aria-hidden="true"> <symbol id="i-heart" viewBox="0 0 24 24"> <path d="M12 21s-7-4.5-9.5-9A5.5 5.5 0 0 1 12 6a5.5 5.5 0 0 1 9.5 6c-2.5 4.5-9.5 9-9.5 9z" fill="currentColor"/> </symbol></svg> <div class="row"> <svg class="icon" style="color: crimson" aria-hidden="true"><use href="#i-heart"/></svg> <svg class="icon" style="color: royalblue" aria-hidden="true"><use href="#i-heart"/></svg> <svg class="icon" style="color: seagreen" aria-hidden="true"><use href="#i-heart"/></svg> <span>Sprite: one symbol, three colours</span></div><div class="row"> <span class="masked"></span><span class="masked alt"></span> <span>mask-image: one file, painted with background-color</span></div>

Preview

Two catches. An external sprite (<use href="/icons.svg#i-heart">) must be same-origin, so you cannot load it from a different CDN domain without serving it from your own. And the old xlink:href attribute is deprecated: plain href works in every current browser.

Match the pairs0/4 matched

Match each job to the embedding method that fits it best.

Choose an item, then its match on the other side.

Theming with currentColor and custom properties

Hard-coded fill="#111" is why icons stay black in dark mode. Use fill="currentColor" (or stroke="currentColor") instead: currentColor is the element's CSS color, inherited from its parent. The icon then matches the text around it, follows :hover and :focus-visible, and switches with your theme for free.

For two-tone icons, give each part a custom property with a fallback. Custom properties inherit into inline SVG and into <use> copies, so one sprite symbol can be recoloured per instance.

HTML & CSS
<style> :root { --bg: white; --fg: #111; --accent: #d33; } .dark { --bg: #111; --fg: #eee; --accent: #ff8a80; } .card { background: var(--bg); color: var(--fg); padding: 16px; display: flex; gap: 12px; align-items: center; } .card button { color: inherit; background: none; border: 1px solid currentColor; padding: 8px 12px; display: inline-flex; gap: 8px; align-items: center; } .card button:hover { color: var(--accent); }</style><div class="card" id="card"> <svg width="32" height="32" viewBox="0 0 24 24" aria-hidden="true"> <circle cx="12" cy="12" r="10" fill="var(--accent)"/> <path d="M7 12l3 3 7-7" fill="none" stroke="currentColor" stroke-width="2.5"/> </svg> <button type="button" onclick="document.getElementById('card').classList.toggle('dark')"> <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/></svg> Toggle theme </button></div>

Preview

Click the button and hover it. Nothing in the SVG mentions a colour value: it reads currentColor and var(--accent), and the theme sets those. None of this reaches an SVG loaded through <img>, because that file is a separate document. Page CSS stops at its edge. That is the main reason UI icons are inline or sprites.

Accessible icons

Every SVG is either decoration or content, and you mark it accordingly. This builds on Accessibility Basics.

  • Decorative (next to visible text that already says the same thing): aria-hidden="true". Add focusable="false" only if you still support very old Internet Explorer behaviour; current browsers do not focus SVG by default.
  • Meaningful on its own (a chart, a status icon with no text): role="img" plus a name. Use aria-label, or a <title> as the first child referenced with aria-labelledby for the widest screen reader support. Charts also need the data in text somewhere: a caption, a summary or a table.
  • Icon-only buttons and links: put the name on the button, not the SVG. <button aria-label="Close"> with an aria-hidden SVG inside. A button's name comes from its content, and an SVG's <title> alone is announced inconsistently.
HTML & CSS
<button type="button" aria-label="Close dialog" style="padding: 8px; line-height: 0"> <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"> <path d="M6 6l12 12M18 6L6 18"/> </svg></button> <svg role="img" aria-labelledby="sales-title" width="160" height="60" viewBox="0 0 160 60"> <title id="sales-title">Sales rose from 20 to 50 units between January and March</title> <rect x="10" y="40" width="30" height="20" fill="steelblue"/> <rect x="60" y="25" width="30" height="35" fill="steelblue"/> <rect x="110" y="10" width="30" height="50" fill="steelblue"/></svg>

Preview

Open DevTools, select the button and look at the Accessibility pane: its computed name is "Close dialog", and the SVG is not in the accessibility tree at all. Two more points: an icon-only button still needs a target of at least 24 by 24 CSS pixels for WCAG 2.2 Target Size (Minimum), so pad the button rather than relying on a 16px glyph. And in Windows high contrast (forced colours) mode, currentColor icons adapt automatically, while hard-coded fills can vanish against the forced background.

Quick check
An icon-only search button contains an inline SVG with <title>Search</title>. What is the most reliable fix for screen readers?
Need a nudge? A hint rules out a wrong answer.

Animating SVG

SVG shapes animate with ordinary CSS. The classic effect is line drawing: set stroke-dasharray to the path's length (one dash as long as the whole line), offset it by the same amount so the dash starts off the end, then animate stroke-dashoffset to 0. pathLength="1" saves you measuring: it tells the browser to treat the path as 1 unit long whatever its real length.

HTML & CSS
<style> .draw path { stroke-dasharray: 1; stroke-dashoffset: 0; /* visible by default */ } @media (prefers-reduced-motion: no-preference) { .draw path { animation: draw 1.6s ease-out both; } .spin { animation: spin 2s linear infinite; transform-box: fill-box; transform-origin: center; } } @keyframes draw { from { stroke-dashoffset: 1; } to { stroke-dashoffset: 0; } } @keyframes spin { to { transform: rotate(1turn); } }</style><svg class="draw" viewBox="0 0 24 24" width="120" height="120" fill="none" stroke="seagreen" stroke-width="1.5" stroke-linecap="round"> <path pathLength="1" d="M3 10 L12 3 L21 10 V20 a1 1 0 0 1 -1 1 H4 a1 1 0 0 1 -1 -1 Z"/></svg><svg viewBox="0 0 100 100" width="120" height="120"> <rect x="10" y="10" width="80" height="80" fill="none" stroke="#ccc"/> <rect class="spin" x="55" y="55" width="25" height="25" fill="darkorange"/></svg>

Preview

The second shape shows the other common trap. CSS transforms on SVG children rotate around the SVG's origin (0,0, the top-left of the viewBox) by default, so the square would orbit the corner. transform-box: fill-box makes transform-origin: center mean the centre of the shape itself. Delete that line and watch it swing. As with any motion, wrap animation in prefers-reduced-motion: no-preference and make the resting state the finished drawing, so nothing is hidden if the animation never runs.

Optimising SVG files

Design tools export a lot of things browsers do not need. A typical export looks like this before cleanup:

What is inside an exported icon
svgxmlns, version, x, y, xml:space, width, height, viewBoxmetadataeditor name, document idssodipodi:namedviewInkscape canvas settingsdefssometimes emptytitle"Artboard 1 Copy 3"pathcoordinates with 6 decimal placespatha second path that could merge with the firstgid="Layer_1"gtransform="translate(-412 -88)"root

Editor metadata. Useless to a browser, and it can leak file paths, usernames or layer names. Remove it.

1/4

SVGO is the standard optimiser, used by most build tools under the hood:

npx svgo icons/home.svg -o icons/home.min.svgnpx svgo -f icons -o icons-optimised

Its default preset is safe for most icons, but check the result: some setups strip the viewBox (which breaks scaling) or merge IDs that your CSS or <use> references depend on. Pin your config in the repo so every icon goes through the same steps, and remember that HTTP compression (gzip or Brotli) shrinks SVG text much further on the wire.

SVG is not always the light option. A photo traced into vectors, or an illustration with thousands of paths and gradients, can be hundreds of kilobytes and slow to render on every paint. If an SVG is bigger than a well-compressed WebP or AVIF of the same image at its display size, use the raster format. Also note that inline SVG shapes are never the Largest Contentful Paint element (only an <image> inside an SVG is a candidate), which matters if your hero is a large inline illustration and you are wondering why LCP picked something else.

Put it in order4 steps

Put these steps for adding a new icon to a design system in a sensible order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
viewBox
The SVG's internal coordinate system (min-x, min-y, width, height), which the browser scales into the element's on-page size.
preserveAspectRatio
How the viewBox fits a box of a different shape: meet (contain), slice (cover) or none (stretch).
path data
The d attribute's command language: M, L, H, V, C, Q, A, Z. Uppercase is absolute, lowercase relative.
currentColor
A keyword that resolves to the element's CSS color, letting icons inherit text colour and theme changes.
symbol and use
A sprite technique: define each icon once as a symbol, then render copies with use href pointing at its id.
transform-box: fill-box
Makes SVG transform origins relative to the shape's own bounding box instead of the SVG canvas.
SVGO
The standard Node tool for removing metadata, rounding coordinates and simplifying SVG files.