SVG Integration
By the end of this lesson you will choose the right way to put an SVG on a page, build an icon set that follows your text colour, label it for screen readers and handle SVG uploads safely.
The SVG & Canvas lesson introduced SVG, viewBox and the basic shapes. Here we go further, into how SVG fits into a real website.
Four ways to put SVG on a page
The same SVG file can reach the page in four ways, and each changes what CSS and JavaScript can do with it.
| Method | Page CSS can style inside? | Scripts inside run? | Cached as a file? | Best for |
|---|---|---|---|---|
Inline <svg> in the HTML | Yes | Page scripts can change it | No, it is part of the page | Icons, charts you style or animate |
<img src="logo.svg"> | No | No | Yes | Logos and illustrations |
CSS background-image | No | No | Yes | Decorative patterns |
<object data="map.svg"> | No | Yes, its own scripts | Yes | Interactive SVG documents |
Through <img> or CSS, the browser treats SVG like a picture: its scripts do not run and it cannot load other files. An <object> loads it as a separate document, like an iframe, so its own scripts run.
Run this example and compare the four copies of the same icon.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Four ways</title>
<style>
body { font-family: system-ui, sans-serif; padding: 16px; color: #b45309; }
.row { display: flex; gap: 24px; flex-wrap: wrap; align-items: end; }
figure { margin: 0; text-align: center; }
.bg { width: 64px; height: 64px; background: url("https://course.ethicscomputer.in/assets/samples/icon.svg") center / contain no-repeat; }
</style>
</head>
<body>
<h1>The same icon, four ways</h1>
<div class="row">
<figure>
<svg width="64" height="64" viewBox="0 0 24 24" aria-hidden="true">
<circle cx="12" cy="12" r="10" fill="currentColor" />
</svg>
<figcaption>Inline</figcaption>
</figure>
<figure>
<img src="https://course.ethicscomputer.in/assets/samples/icon.svg" alt="" width="64" height="64">
<figcaption>img</figcaption>
</figure>
<figure>
<div class="bg"></div>
<figcaption>CSS background</figcaption>
</figure>
<figure>
<object data="https://course.ethicscomputer.in/assets/samples/icon.svg" type="image/svg+xml" width="64" height="64" aria-hidden="true"></object>
<figcaption>object</figcaption>
</figure>
</div>
</body>
</html>Change color on body to teal and run it again. Only the inline circle changes, because only inline SVG is part of the page's DOM.
viewBox and scaling
The viewBox attribute takes four numbers: min-x min-y width height. It defines the drawing's own grid. Think of graph paper: the icon is drawn on a 24 by 24 sheet, and the browser enlarges or shrinks the sheet to fit your box.
<!-- One drawing, three sizes: the viewBox never changes -->
<svg viewBox="0 0 24 24" width="16" height="16">...</svg>
<svg viewBox="0 0 24 24" width="48" height="48">...</svg>
<svg viewBox="0 0 24 24" style="width: 100%; height: auto">...</svg>Three rules help in practice:
- Always set a
viewBox. Without it, the SVG cannot scale. - Set
widthandheighttoo. They stop a huge icon flashing on screen before your CSS loads. - If the box shape differs from the
viewBoxshape, the drawing is centred without stretching.preserveAspectRatio="none"stretches it instead, and"xMidYMid slice"fills the box and crops the edges.
Paths: the shape behind every icon
Most icons are made of <path> elements. The d attribute is a list of drawing commands, like directions given to an auto driver: "start here, go straight to there, curve round to that corner".
| Command | Meaning | Example |
|---|---|---|
M x y | Move the pen without drawing | M 3 11 |
L x y | Straight line to a point | L 12 3 |
H x / V y | Horizontal or vertical line | V 21 |
C x1 y1 x2 y2 x y | Curve with two control points | C 5 15 2 11 2 7.5 |
A rx ry rotation large sweep x y | Arc, part of an ellipse | A 4.5 4.5 0 0 1 12 6 |
Z | Close the shape back to the start | Z |
Upper-case letters use positions on the grid. Lower-case letters (l, c, a) measure from the current point. Design tools write long paths for you, but reading short ones helps you fix icons.
Build an icon sprite
Repeating one path in ten buttons makes the page heavy. A sprite stores each icon once and shows copies. Build one in three steps:
- Draw each icon once as a
<symbol>with its ownviewBox. A symbol is never drawn by itself; it is a rubber stamp. - Use
fillorstrokeset tocurrentColor, a keyword meaning "this element's CSScolor". The icon then matches the text, including hover colours. - Press the stamp with
<use href="#id">wherever you need the icon, and label each use.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Icon sprite</title>
<style>
body { font-family: system-ui, sans-serif; padding: 16px; }
button { display: inline-flex; align-items: center; gap: 6px; font: inherit;
padding: 8px 14px; border: 1px solid #ccc; background: white; color: #1f2937; }
button:hover { color: #c2410c; border-color: currentColor; }
.icon { width: 1.25em; height: 1.25em; }
</style>
</head>
<body>
<!-- The sprite: drawn once, hidden from view -->
<svg hidden>
<symbol id="i-home" viewBox="0 0 24 24">
<path d="M3 11 L12 3 L21 11 M5 9 V21 H19 V9" fill="none" stroke="currentColor" stroke-width="2" />
</symbol>
<symbol id="i-heart" viewBox="0 0 24 24">
<path d="M12 21 C5 15 2 11 2 7.5 A4.5 4.5 0 0 1 12 6 A4.5 4.5 0 0 1 22 7.5 C22 11 19 15 12 21 Z" fill="currentColor" />
</symbol>
</svg>
<h1>Ananya's Handloom Store</h1>
<!-- Decorative icon: the button text already names the action -->
<button type="button">
<svg class="icon" aria-hidden="true"><use href="#i-home" /></svg>
Home
</button>
<!-- Icon-only button: the name comes from aria-label -->
<button type="button" aria-label="Add to wishlist">
<svg class="icon" aria-hidden="true"><use href="#i-heart" /></svg>
</button>
<!-- A meaningful graphic on its own: title and desc -->
<p>
<svg width="48" height="48" viewBox="0 0 24 24" role="img" aria-labelledby="fav-t fav-d" style="color: crimson">
<title id="fav-t">Customer favourite</title>
<desc id="fav-d">A red heart shown on products with the most wishlist saves.</desc>
<use href="#i-heart" />
</svg>
</p>
</body>
</html>What you should see: two buttons whose icons turn orange on hover, and a red heart below. The <use> copies inherit the button's color, and the paths use currentColor.
A sprite can also live in its own file: <use href="/icons.svg#i-home">. The file must come from the same origin as the page, because <use> does not load SVG from other sites.
Accessible SVG
The sprite example shows the three common cases:
- Decorative, next to text. Add
aria-hidden="true"so screen readers skip it. The text already says "Home". - Icon-only control. Hide the SVG and name the button with
aria-label. - Meaningful on its own. Add
role="img", a<title>as the first child and a<desc>for detail. Linking both witharia-labelledbygives the most reliable screen reader support.
For SVG in an <img>, use alt as for any image. ARIA Roles & Attributes explains role, aria-label and aria-hidden in depth.
Handling SVG uploaded by users
SVG is code, not just a picture. A file can contain <script> elements, event attributes such as onload, javascript: links and <foreignObject>, which embeds HTML. If Farhan uploads such a file to your college notice board and you paste it inline, his script runs with your users' logins. That is a cross-site scripting (XSS) attack.
Safe habits, strongest first:
- If you do not need vectors, convert uploads to PNG or WebP on the server.
- Otherwise, run it through a well-maintained sanitiser that removes scripts, event attributes,
foreignObjectand external links. DOMPurify, for example, has an SVG profile. - Show user SVG with
<img>, never inline. Scripts inside an<img>do not run. - A visitor who opens the file's URL directly would run its scripts. Serve uploads from a separate domain, or with
Content-Disposition: attachmentand a strict Content Security Policy.
You will learn the server side of this in XSS Prevention and Content Security Policy.
Common mistakes
- Missing
viewBox. The SVG cannot scale and gets clipped. - Hard-coded colours in icons.
fill="#000"ignores your CSS; usecurrentColor. - Unlabelled icon-only buttons. Screen readers announce just "button".
- Inlining uploaded SVG. Always sanitise it and show it with
<img>.
Interview questions
1. When would you use inline SVG instead of an img tag?
Use inline SVG when page CSS or JavaScript must reach the shapes, such as currentColor icons or animated charts. Use <img> for logos and illustrations, because the file is cached and its scripts cannot run.
2. What does the viewBox attribute do?
It sets the SVG's internal coordinate system with four numbers: min-x, min-y, width and height. The browser maps that grid onto the element's actual size, which is what lets one drawing scale cleanly to any size.
3. What is currentColor and why is it useful for icons?
currentColor is a CSS keyword that takes the element's computed color. Used for fill or stroke, it makes the icon follow the text, hover and theme colours automatically.
4. How do you make an SVG accessible?
If it is decorative, add aria-hidden="true". If it carries meaning, give it role="img" and a <title> linked with aria-labelledby, plus a <desc> for more detail. For SVG in <img>, use alt.
5. Why is it dangerous to accept SVG uploads?
SVG can contain scripts, event handlers and embedded HTML. If it is inlined or opened directly from your domain, that code runs in your origin, which is XSS. Sanitise uploads, display them with <img> and serve them from a separate domain.
Key points
- Inline SVG can be styled and scripted by the page;
<img>and CSS backgrounds are cached and run no scripts;<object>is a separate document. viewBoxdefines the drawing's grid; always set it, pluswidthandheight.fill="currentColor"makes icons follow the text colour.- A sprite of
<symbol>elements reused with<use href>keeps icons in one place. - Hide decorative SVG with
aria-hidden; give meaningful SVGrole="img"with<title>andaria-labelledby. - Treat uploaded SVG as code: sanitise it, show it with
<img>and serve it safely.
Exercise
Make a sprite with two icons for a bus ticket site in Rohtak: a "tick" (M4 12 L10 18 L20 6 with a stroke) and a "cross" (two lines from corner to corner). Use them in two buttons: "Confirm booking" with a decorative tick, and an icon-only "Cancel" button with the cross. Both icons must follow the button text colour, and the cancel button must turn red on hover.
Show solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bus tickets</title>
<style>
button { display: inline-flex; align-items: center; gap: 6px; padding: 8px 12px; color: #14532d; }
.cancel:hover { color: #b91c1c; }
.icon { width: 1.2em; height: 1.2em; }
</style>
</head>
<body>
<svg hidden>
<symbol id="i-tick" viewBox="0 0 24 24">
<path d="M4 12 L10 18 L20 6" fill="none" stroke="currentColor" stroke-width="2.5" />
</symbol>
<symbol id="i-cross" viewBox="0 0 24 24">
<path d="M5 5 L19 19 M19 5 L5 19" fill="none" stroke="currentColor" stroke-width="2.5" />
</symbol>
</svg>
<button type="button">
<svg class="icon" aria-hidden="true"><use href="#i-tick" /></svg>
Confirm booking
</button>
<button type="button" class="cancel" aria-label="Cancel booking">
<svg class="icon" aria-hidden="true"><use href="#i-cross" /></svg>
</button>
</body>
</html>Each icon is drawn once and reused with <use>. The strokes use currentColor, so the cross turns red on hover, and the icon-only button is named by aria-label.
Quick Quiz
1. Which way of adding an SVG lets page CSS change the colour of its shapes?
Only inline SVG is part of the page's DOM.
2. What does fill="currentColor" do?
currentColor takes the computed color, so the icon follows the text colour.
3. What is the purpose of <symbol> in an SVG sprite?
A symbol is not rendered by itself; <use href="#id"> stamps copies of it.
4. A user uploads an SVG to your site. What is the safest way to show it?
Scripts inside an <img> never run, and sanitising removes dangerous code before anyone opens the file directly.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
