Cheat sheet #7

Adding SVG to webpages

A cheat sheet for web design students. SVG is a sharp, lightweight image format for logos, icons and illustrations. Learn the four ways to put SVG on a page, and the strengths and weaknesses of each one.

The short version

Choose a method according to what the graphic needs to do.

1. <img> just show a picture 2. inline SVG style or script it with CSS and JavaScript 3. symbol + use one icon, used again and again 4. CSS decoration added by the stylesheet
On this cheat sheet

Introduction to SVG

What is SVG?

SVG (Scalable Vector Graphics) is an image format that’s written as text. Instead of storing a grid of coloured pixels, as JPEG and PNG do, it stores a set of instructions for drawing shapes: a circle here, a line there, a curve in this colour. The browser then draws the shapes at whatever size is needed. SVG is based on XML, which is why its syntax is stricter than HTML’s.

A complete SVG graphic
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <circle cx="12" cy="12" r="10" fill="#2a5bd7" /> <path d="M7 12.5l3.5 3.5L17 9" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" /> </svg>
PartWhat it does
<svg>The container for the whole graphic
viewBox="0 0 24 24"The drawing’s own coordinate grid (x, y, width, height). It is what lets the graphic scale to any size, so always include it.
xmlns="http://www.w3.org/2000/svg"Declares that this is SVG. Required in a separate .svg file.
<circle>, <rect>, <line>, <polygon>, <path>The shapes. path draws any outline, using a compact set of commands in its d attribute.
<text>, <g>, <title>Text, a group of shapes, and an accessible name
fill, stroke, stroke-widthThe colour inside a shape, the colour of its outline, and the outline thickness

Benefits of SVG

Use SVG for
  • Logos
  • Icons and UI symbols
  • Flat or line illustrations
  • Diagrams, charts and maps
  • Decorative shapes and patterns
Don’t use SVG for
  • Photographs. Their millions of subtle colour changes can’t be described by a few shapes, so a traced photo makes a huge, slow file.
  • Screenshots
  • Highly detailed painterly images
Use JPEG, WebP or AVIF for these types of image.

Optimising SVG

An SVG is typically created in a graphics application such as Adobe Illustrator or Affinity, and these applications always add unnecessary code when the graphic is exported as an SVG file. So, before you use an SVG, always optimise it to remove the clutter and optimise the paths. This will reduce the file size to around 70% of the original, which is better for your users. The best way to optimise SVG files is with SVGOMG, an online tool where you can simply drag and drop your SVG files.

The four methods at a glance

MethodLooks likePage CSS can style inside?Best for
1. External file with img<img src="logo.svg" alt="">NoLogos and fixed illustrations
2. Inline SVG<svg>…</svg> in the HTMLYes, fullyInteractive or animated graphics
3. Symbol and use<use href="#icon-tick">Partly (colour, via inheritance)Icon sets used many times
4. CSS generated contenturl("data:image/svg+xml,…")NoDecorative extras added by CSS

1. An external SVG file with the img element

Treat the SVG like any other image

Save the graphic as a separate .svg file (following the naming rules in cheat sheet 1) and display it with <img>, exactly as you would a JPEG or PNG.

images/tick-icon.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <circle cx="12" cy="12" r="10" fill="#2a5bd7" /> <path d="M7 12.5l3.5 3.5L17 9" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" /> </svg>
In the HTML page
<img src="images/tick-icon.svg" alt="Order confirmed" width="48" height="48">
Pros
  • It’s the simplest method, with one familiar line of HTML.
  • It keeps your HTML clean and readable.
  • The browser caches the file, so it’s downloaded once and reused on every page.
  • It works with width, height, loading="lazy", srcset and <picture>.
  • There’s only one file to update when the graphic changes.
Cons
  • Your page CSS can’t reach inside it, so you can’t change its colours or style its parts.
  • There’s no interaction, so scripts and links inside the file don’t work.
  • It needs an extra file request.
  • It can’t inherit the surrounding text colour. The colours are fixed in the file, although the file can contain its own <style>.

Example use case: a site logo in the header, or a large illustration on an “About us” page. In both cases, the graphic is simply shown, it’s never restyled, and it appears on several pages.

2. Inline SVG in the HTML

Put the SVG code directly in the page

The <svg> element is written straight into your HTML, and each shape becomes an element in the page, just like a p or a div. Because the shapes are part of the page, your CSS and JavaScript can style and control every one of them, using the selectors from cheat sheet 6.

<svg viewBox="0 0 24 24" width="48" height="48" role="img" aria-labelledby="tick-title"> <title id="tick-title">Order confirmed</title> <circle cx="12" cy="12" r="10" /> <path d="M7 12.5l3.5 3.5L17 9" /> </svg> /* In your stylesheet: shapes take fill and stroke, not color */ svg circle { fill: #2a5bd7; } svg circle:hover { fill: #176b3f; } svg path { fill: none; stroke: #fff; stroke-width: 2; stroke-linecap: round; }
LIVE RESULT (hover over the icon) Order confirmed

SVG is XML, so the syntax is strict

HTML forgives a lot of mistakes, but SVG doesn’t, because it follows the stricter rules of XML (the same rules as XHTML). A single slip can make the rest of the graphic disappear.

RuleCorrectWrong
Every element must be closed. Shapes with no content end in />. Unlike HTML’s br or img, circle and path are not void elements, so left open, they swallow the shapes that follow.<circle cx="12" cy="12" r="10" /><circle cx="12" cy="12" r="10">
Attribute values are always quoted.r="10"r=10
Names are case-sensitive. Some contain capitals.viewBox, linearGradient, clipPathviewbox, lineargradient
Properly nested. Close inner elements before outer ones.<g><path /></g><g><path></g></path>
Special characters are escaped in text and values.Q&amp;AQ&A
Ids must be unique across the whole page, or gradients and masks pick the wrong target.id="tick-title" onceThe same id twice
Pros
  • You have full control. CSS can style any shape, including its hover and focus states.
  • JavaScript can change and animate parts of the graphic, and respond to clicks on them.
  • It inherits the text colour through currentColor.
  • There’s no extra file request.
  • You can attach accessible names and descriptions.
Cons
  • Bulks up the HTML and makes it harder to read.
  • It isn’t cached separately. If it’s repeated on several pages, or used several times on one page, the code is repeated every time.
  • The strict syntax is easy to break.
  • Its ids can clash with the rest of the page.

Example use case: an interactive chart with bars that change colour on hover, an animated loading spinner, or a button icon that takes on the button’s text colour.

3. Define SVG with <symbol> in HTML and include with <use>

Define once, use many times

Put each reusable graphic inside a <symbol> in a hidden SVG, which is normally placed near the top of the body. Every <symbol> needs a unique id and its own viewBox. You can then display it wherever you like with <use>, using an href that points to the symbol’s id with a #.

Define the symbols once (hidden)
<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0" style="position:absolute" aria-hidden="true"> <symbol id="icon-tick" viewBox="0 0 24 24"> <circle cx="12" cy="12" r="10" fill="currentColor" /> <path d="M7 12.5l3.5 3.5L17 9" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" /> </symbol> </svg>
Use it anywhere, as often as you like
<svg class="ico blue" width="48" height="48" aria-hidden="true"><use href="#icon-tick" /></svg> <svg class="ico green" width="48" height="48" aria-hidden="true"><use href="#icon-tick" /></svg> /* The shapes use currentColor, so each copy takes its own text colour */ .blue { color: #2a5bd7; } .green { color: #176b3f; }
LIVE RESULT (one definition, three uses, three colours)
Pros
  • The drawing is written once, however many times it appears.
  • It keeps the HTML tidy, because each use is one short line.
  • Colour and size are easy to change for each use.
  • There’s no extra file request (with an in-page sprite).
  • Each symbol scales through its own viewBox.
Cons
  • You can’t restyle or animate the individual shapes inside from the page.
  • The symbols still have to be included in every page that needs them (unless you use a sprite file).
  • The hidden SVG must come first, and its ids must be unique.
  • It needs a little more setup than a plain img.

Example use case: an icon set, such as search, menu, cart and tick icons, that appears many times across a page’s buttons, navigation and lists, and needs to match the surrounding text colour.

4. SVG as generated content in CSS

Put the SVG inside your stylesheet

CSS can’t contain SVG tags directly, so the graphic is written as a data URI. That’s the SVG code, squeezed onto a single line and placed inside url(). It’s usually attached to a ::before or ::after pseudo-element (see cheat sheet 6), or used as a background image, and the HTML needs no changes at all.

/* Add an "opens another site" icon after every external link */ a[href^="https"]::after { content: ""; display: inline-block; width: 1.0em; height: 1.0em; margin-left: 0.3em; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%232a5bd7' stroke-width='2.5'%3E%3Cpath d='M14 4h6v6M20 4L10 14M18 14v6H4V6h6'/%3E%3C/svg%3E") center / contain no-repeat; }
LIVE RESULT (the icon is added by the stylesheet only) Visit our partner

The special SVG syntax for this method

Inside a CSS data URI, the SVG is treated as a separate image file, so the rules are different from those for inline SVG:

RequirementWhyExample
Start with data:image/svg+xml,Tells the browser what kind of data followsurl("data:image/svg+xml,…")
Include xmlnsRequired, as in a standalone file. It is optional when inline, but here the image won’t render without it.xmlns='http://www.w3.org/2000/svg'
Use single quotes inside the SVGThe outer url("…") already uses double quotesviewBox='0 0 24 24'
Encode # as %23A raw # starts a URL fragment and cuts the data short. This affects every hex colour.fill='%232a5bd7'
Encode < as %3C and > as %3EKeeps the URL valid in all browsers%3Csvg … %3E
Keep it on one lineA line break would break the URLNo line breaks inside url()
Colours are fixedThe image can’t see your page’s colours, so currentColor doesn’t workUse a literal colour, or the mask trick below

You can make the required syntax changes in a code editor, using find and replace, or you can use the Convert SVG to CSS url() utility to make your SVG ready for your stylesheet in one step.

There are two ways to place it:

Tip: colouring with a mask. To make a CSS icon follow the text colour, use the SVG as a mask over a block of currentColor. Only the shape of the SVG shows through, in whatever colour the text happens to be:

.icon::before { content: ""; display: inline-block; width: 1.5rem; height: 1.5rem; background-color: currentColor; mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Ccircle cx='12' cy='12' r='10'/%3E%3C/svg%3E") center / contain no-repeat; }
LIVE RESULT (the circle takes the text colour)
Pros
  • It keeps decorative graphics out of the HTML, so the content stays clean.
  • A single CSS rule can add the graphic to many elements automatically.
  • CSS decides when the graphic appears, using selectors, media queries and states such as :hover.
  • There’s no extra file request.
Cons
  • It’s for decoration only. Generated images have no alt text, and they can’t be selected or interacted with, so important content belongs in the HTML.
  • The strict encoding makes the code hard to read and edit.
  • Page CSS can’t style the inside of the image, and currentColor doesn’t work without the mask trick.
  • Long data strings bulk up the stylesheet, and using the same graphic in several rules repeats the data each time.

Example use case: an external-link icon added automatically to every link that starts with https, custom list bullets, or a dropdown arrow on a select element.

Accessibility at a glance

MethodMeaningful graphicDecorative graphic
1. imgalt="Hill Café logo"alt=""
2. Inlinerole="img" with a <title> and aria-labelledbyaria-hidden="true"
3. Symbol and userole="img" and aria-label on the outer svgaria-hidden="true" on the outer svg
4. CSSNot suitable. Put it in the HTML.Nothing needed: it’s invisible to assistive technology

Which method should I use?

1. img2. Inline3. Symbol + use4. CSS
Page CSS can style the shapesNoYesNo (colour only)No
JavaScript and interactionNoYesLimitedNo
Follows text colour (currentColor)NoYesYesOnly with a mask
Cached separately by the browserYesNoNo (in-page sprite)No (part of the CSS)
Keeps the HTML cleanYesNoMostlyYes
Reuse the same graphicEasyRepeat the codeEasiestRepeat the rule
Suitable for meaningful contentYesYesYesNo: decoration only
Best forLogos, illustrationsInteractive and animated graphicsIcon setsDecorative extras

A good default is to use img for anything that’s simply shown, then move to inline SVG or symbols when you need to style, animate or reuse the graphic.

Common mistakes

MistakeFix
Missing xmlns in a .svg file or CSS data URIAdd xmlns="http://www.w3.org/2000/svg"
No viewBox, so the graphic won’t scaleAdd one, matching the drawing’s coordinates
An unclosed shape: <path d="…">Close it: <path d="…" />
A raw # in a data URI colourWrite %23 instead
No alt on an imgDescribe it, or use alt="" if decorative
Using color to colour a shapeUse fill and stroke, or fill="currentColor"
Leaving the <?xml?> line or editor metadata in inline SVGDelete everything except the <svg> element
The same id in two inline SVGsMake every id unique on the page
<use href="icon-tick"> without the #Write href="#icon-tick"
Using SVG for a photographUse JPEG, WebP or AVIF

Check before you upload

Learn more

Tip: although you can create simple SVG images by writing the code yourself, it’s best to use a dedicated vector graphics application, such as Adobe Illustrator or Affinity, so that they can be edited visually.