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 stylesheetOn 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.
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-width
The colour inside a shape, the colour of its outline, and the outline thickness
Benefits of SVG
It scales without losing quality. SVG stays sharp at any size and on any screen, including high-density displays, so you don’t need several versions of the same image.
Files are small for simple graphics, and often much smaller than the equivalent PNG.
It can be styled and scripted. Depending on the method you use, CSS and JavaScript can change colours, add hover effects and animate parts of the image.
It’s text-based. That means it can be edited in a code editor, it compresses well, and it can carry an accessible title.
Transparency is built in.
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
Method
Looks like
Page CSS can style inside?
Best for
1. External file with img
<img src="logo.svg" alt="">
No
Logos and fixed illustrations
2. Inline SVG
<svg>…</svg> in the HTML
Yes, fully
Interactive or animated graphics
3. Symbol and use
<use href="#icon-tick">
Partly (colour, via inheritance)
Icon sets used many times
4. CSS generated content
url("data:image/svg+xml,…")
No
Decorative 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.
LIVE RESULT (this demo uses an embedded copy of the file)
The standalone file must include xmlns="http://www.w3.org/2000/svg", or the browser won’t render it.
Always give the img an alt attribute. Use a description for meaningful graphics, and alt="" for decorative ones.
Set the width and height attributes so that the page doesn’t jump while it loads.
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)
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.
Rule
Correct
Wrong
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, clipPath
viewbox, 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&A
Q&A
Ids must be unique across the whole page, or gradients and masks pick the wrong target.
id="tick-title" once
The same id twice
When you paste code exported from a design tool, delete the <?xml ... ?> line, any <!DOCTYPE>, and any editor metadata. None of these belong inside an HTML page.
In a standalone .svg file or an XHTML page, keep xmlns="http://www.w3.org/2000/svg". In an ordinary HTML page it’s optional, but harmless.
Make the graphic accessible. For meaningful graphics, use role="img" with a <title> and aria-labelledby. For decorative graphics, use aria-hidden="true".
Use fill="currentColor" on shapes so that they inherit the surrounding text colour.
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 #.
<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)
Give each outer <svg> a width and a height (or size it in CSS). If you don’t, it can balloon to fill its container.
Use the modern href attribute, not the old xlink:href.
The outer <svg> can be styled, sized and made accessible just like any inline SVG. Add aria-hidden="true" if it’s decorative, or role="img" and aria-label if it carries meaning.
Page CSS can’t select the shapes inside a symbol. Only inherited properties, such as color and CSS custom properties, pass through, so design the symbol around currentColor.
A symbol can also live in a separate sprite file, as in <use href="icons.svg#icon-tick" />. However, the file must come from the same site, and it won’t load when you open pages straight from your drive without a server.
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:
Requirement
Why
Example
Start with data:image/svg+xml,
Tells the browser what kind of data follows
url("data:image/svg+xml,…")
Include xmlns
Required, 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 SVG
The outer url("…") already uses double quotes
viewBox='0 0 24 24'
Encode # as %23
A raw # starts a URL fragment and cuts the data short. This affects every hex colour.
fill='%232a5bd7'
Encode < as %3C and > as %3E
Keeps the URL valid in all browsers
%3Csvg … %3E
Keep it on one line
A line break would break the URL
No line breaks inside url()
Colours are fixed
The image can’t see your page’s colours, so currentColor doesn’t work
Use 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:
As a background image (shown above). You control its size and position with width, height, background-size and background-position, which makes this the most flexible approach.
With content: url(...). The image appears inline, at the size set by the width and height attributes on the SVG itself, so you’ll need to add them, as in width='16' height='16'.
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:
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
Method
Meaningful graphic
Decorative graphic
1. img
alt="Hill Café logo"
alt=""
2. Inline
role="img" with a <title> and aria-labelledby
aria-hidden="true"
3. Symbol and use
role="img" and aria-label on the outer svg
aria-hidden="true" on the outer svg
4. CSS
Not suitable. Put it in the HTML.
Nothing needed: it’s invisible to assistive technology
Which method should I use?
1. img
2. Inline
3. Symbol + use
4. CSS
Page CSS can style the shapes
No
Yes
No (colour only)
No
JavaScript and interaction
No
Yes
Limited
No
Follows text colour (currentColor)
No
Yes
Yes
Only with a mask
Cached separately by the browser
Yes
No
No (in-page sprite)
No (part of the CSS)
Keeps the HTML clean
Yes
No
Mostly
Yes
Reuse the same graphic
Easy
Repeat the code
Easiest
Repeat the rule
Suitable for meaningful content
Yes
Yes
Yes
No: decoration only
Best for
Logos, illustrations
Interactive and animated graphics
Icon sets
Decorative 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
Mistake
Fix
Missing xmlns in a .svg file or CSS data URI
Add xmlns="http://www.w3.org/2000/svg"
No viewBox, so the graphic won’t scale
Add one, matching the drawing’s coordinates
An unclosed shape: <path d="…">
Close it: <path d="…" />
A raw # in a data URI colour
Write %23 instead
No alt on an img
Describe it, or use alt="" if decorative
Using color to colour a shape
Use fill and stroke, or fill="currentColor"
Leaving the <?xml?> line or editor metadata in inline SVG
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.