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.
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".widthandheight(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.
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.
| Command | Meaning | Arguments |
|---|---|---|
M / m | Move the pen without drawing | x y |
L / l | Line to | x y |
H / h, V / v | Horizontal or vertical line | x, or y |
C / c | Cubic Bezier curve | two control points, then the end point |
Q / q | Quadratic Bezier curve | one control point, then the end point |
A / a | Elliptical arc | rx ry rotation large-arc sweep x y |
Z / z | Close the shape back to its start | none |
Here is a home icon in the style of the open source Lucide set, taken apart. Edit the numbers and watch the shape change.
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.
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"/>
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-widthis 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.
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.
| Method | Styleable with page CSS | Cached as a file | Script runs | Best for |
|---|---|---|---|---|
Inline <svg> in the HTML | Yes, fully | No, part of the HTML | Yes (it is your DOM) | Icons that change colour, interactive charts |
<img src="logo.svg"> | No | Yes | No | Logos, illustrations, anything you do not need to restyle |
CSS background-image or mask-image | Colour only, via the mask trick | Yes | No | Decorative icons in CSS, tinting one file many colours |
Sprite: <symbol> + <use href="#id"> | Yes, through currentColor and custom properties | Inline sprite: no. External same-origin file: yes | Inline: yes | Many 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.
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 each job to the embedding method that fits it best.
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.
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". Addfocusable="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. Usearia-label, or a<title>as the first child referenced witharia-labelledbyfor 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 anaria-hiddenSVG inside. A button's name comes from its content, and an SVG's<title>alone is announced inconsistently.
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.
<title>Search</title>. What is the most reliable fix for screen readers?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.
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:
Editor metadata. Useless to a browser, and it can leak file paths, usernames or layer names. Remove it.
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-optimisedIts 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 these steps for adding a new icon to a design system in a sensible order.
- Tap the steps below in the right order.
- 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.