Skip to main content

SVG Graphics in HTML

Mentor's Note: SVG is like teaching the browser to draw with math! Instead of storing millions of colored dots (pixels), you give the browser instructions like "draw a circle here" or "draw a line from A to B." The result? Graphics that stay razor-sharp no matter how much you zoom in! 🎯✨

📚 Educational Content: This guide covers SVG (Scalable Vector Graphics) — from basic shapes to practical usage in HTML.


🎯 Learning Objectives

By the end of this lesson, students will be able to:

  • Explain the difference between raster and vector graphics
  • Create basic SVG shapes (circle, rectangle, line, ellipse, polygon, path)
  • Use inline SVG directly in HTML documents
  • Choose between inline SVG and <img> SVG based on project needs
  • Understand when to use SVG vs Canvas

🌟 The Scenario: The Magic Drawing Board

Imagine you have a whiteboard that understands mathematical commands:

CommandResult
circle at (50,50) radius 40🟢 A perfect circle appears
rectangle from (10,10) width 80 height 50▬ A crisp rectangle appears
line from (0,0) to (100,100)╱ A diagonal line appears

SVG works exactly like this! You give coordinates and instructions, and the browser draws perfect shapes. No pixelation. No blur. Ever.

💡 Real-world analogy: A raster image is like a mosaic made of tiny tiles. A vector graphic is like a blueprint that tells someone exactly how to build something. The blueprint stays sharp at any scale.


📖 What is SVG?

SVG stands for Scalable Vector Graphics. It's an XML-based format for describing 2D graphics using text.

Key Benefits:

  • Resolution-independent — looks sharp on any screen, from smartwatches to 4K monitors
  • Small file sizes — especially for logos, icons, and illustrations
  • Editable with code — open an SVG file in any text editor and modify it
  • Stylable with CSS — change colors, sizes, and effects just like HTML elements
  • Scriptable with JavaScript — animate and interact with SVG elements
  • Accessible — add titles, descriptions, and ARIA attributes

Raster vs Vector


🔢 The SVG Coordinate System

SVG uses a coordinate system where (0,0) starts at the top-left corner. The x value increases to the right, and the y value increases downward.

💡 Key insight: In SVG, cx and cy mark the center of a circle. x and y mark the top-left corner of a rectangle. This is just like positioning elements in CSS!


⚙️ Basic SVG Shapes

All SVG graphics live inside an <svg> element. Think of it as your drawing canvas:

<svg width="400" height="300" xmlns="http://www.w3.org/2000/svg">
<!-- Shapes go here -->
</svg>

1. 🔵 Circle (<circle>)

<svg width="200" height="200">
<circle cx="100" cy="100" r="50" fill="blue" />
</svg>
AttributeMeaningExample
cxCenter X positioncx="100"
cyCenter Y positioncy="100"
rRadiusr="50"

2. 🟦 Rectangle (<rect>)

<svg width="300" height="200">
<rect x="50" y="50" width="200" height="100" fill="red" rx="10" />
</svg>
AttributeMeaningExample
xLeft positionx="50"
yTop positiony="50"
widthWidthwidth="200"
heightHeightheight="100"
rxCorner radiusrx="10"
ryCorner radius (vertical)ry="10"

3. ➖ Line (<line>)

<svg width="300" height="100">
<line x1="10" y1="10" x2="290" y2="90" stroke="green" stroke-width="4" />
</svg>
AttributeMeaningExample
x1Start Xx1="10"
y1Start Yy1="10"
x2End Xx2="290"
y2End Yy2="90"

4. 🥚 Ellipse (<ellipse>)

<svg width="300" height="200">
<ellipse cx="150" cy="100" rx="120" ry="60" fill="purple" />
</svg>
AttributeMeaningExample
cxCenter Xcx="150"
cyCenter Ycy="150"
rxX-axis radiusrx="120"
ryY-axis radiusry="60"

5. ⬡ Polygon (<polygon>)

<svg width="200" height="200">
<polygon points="100,10 190,150 10,150" fill="orange" stroke="black" stroke-width="2" />
</svg>
AttributeMeaningExample
pointsComma/space-separated X,Y pairspoints="100,10 190,150 10,150"

6. ✏️ Path (<path>)

The <path> element is the most powerful — it can draw anything:

<svg width="200" height="200">
<path d="M 10 100 C 10 10, 190 10, 190 100 S 10 190, 10 100" fill="none" stroke="red" stroke-width="4" />
</svg>
CommandMeaning
M x yMove to (x,y) — lift the pen
L x yLine to (x,y) — draw straight
C x1 y1, x2 y2, x yCubic Bézier curve
Q x1 y1, x yQuadratic Bézier curve
A rx ry x-axis-rotation large-arc sweep x yArc
ZClose path — return to start

🎨 SVG Attributes Reference

AttributeUsed WithPurposeExample
cxcircle, ellipseCenter Xcx="50"
cycircle, ellipseCenter Ycy="50"
rcircleRadiusr="40"
rxrect, ellipseX radius / corner radiusrx="10"
ryrect, ellipseY radius / corner radiusry="10"
xrect, text, imageLeft positionx="10"
yrect, text, imageTop positiony="10"
widthrect, svg, imageWidthwidth="100"
heightrect, svg, imageHeightheight="100"
fillAll shapesInterior colorfill="blue"
strokeAll shapesOutline colorstroke="black"
stroke-widthAll shapesOutline thicknessstroke-width="2"
opacityAll shapesTransparency (0–1)opacity="0.5"
transformAll shapesTranslate/rotate/scaletransform="rotate(45 100 100)"

Example combining attributes:

<svg width="400" height="200">
<!-- Filled circle with border -->
<circle cx="80" cy="100" r="60" fill="#3498db" stroke="#2c3e50" stroke-width="4" />

<!-- Transparent rectangle with dashed border -->
<rect x="200" y="40" width="160" height="120" fill="none" stroke="#e74c3c" stroke-width="3" stroke-dasharray="8 4" />

<!-- Semi-transparent ellipse -->
<ellipse cx="300" cy="100" rx="40" ry="25" fill="#2ecc71" opacity="0.6" />
</svg>

🖥️ SVG in HTML

You can use SVG in two ways in HTML.

Inline SVG

Write SVG code directly in your HTML. This gives you full control:

<!DOCTYPE html>
<html>
<head>
<title>Inline SVG Example</title>
<style>
.star { fill: gold; transition: fill 0.3s; }
.star:hover { fill: orange; }
</style>
</head>
<body>
<h1>My SVG Star</h1>

<svg width="200" height="200" viewBox="0 0 100 100">
<polygon class="star" points="50,5 63,35 95,35 69,55 77,85 50,65 23,85 31,55 5,35 37,35" />
<text x="50" y="55" text-anchor="middle" fill="white" font-size="10"></text>
</svg>

<p>Hover the star to see it change color!</p>
</body>
</html>

Best for: When you need to style, script, or animate SVG elements individually.

SVG via <img> Tag

Reference an external .svg file like any other image:

<img src="logo.svg" alt="Company Logo" width="200" height="100" />

Best for: Simple display when you don't need to manipulate the graphic.

Inline SVG vs <img> SVG


🎯 SVG Icons

Many modern icon libraries use SVG because of its scalability and customizability:

LibrarySiteNotes
Heroiconsheroicons.comFree, SVG icons by Tailwind CSS team
Font Awesomefontawesome.comFree tier available, SVG + font versions
Feather Iconsfeathericons.comOpen-source, clean design
Material Iconsfonts.google.com/iconsGoogle's icon set
SVG Reposvgrepo.comLarge collection of free SVG vectors

Example: Using a Heroicon inline

<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
</svg>

This is the Heart icon from Heroicons — a single <path> element!


🆚 SVG vs Canvas

FeatureSVGCanvas
TypeVectorRaster
ScalingPerfect at any sizePixel-based, gets blurry
PerformanceBetter for few elements (< 1000)Better for many elements (> 1000)
AccessibilityBuilt-in (text elements, titles)Requires extra work
Event handlingPer-element events (click, hover)Manual hit detection
AnimationCSS + SMIL animationsJavaScript loops
Use caseIcons, logos, illustrationsGames, data viz, photo filters

💡 Common SVG Use Cases

1. Logo with Hover Effect

<svg width="120" height="120" viewBox="0 0 120 120">
<style>
.logo-circle { fill: #4A90D9; transition: fill 0.3s; }
.logo-circle:hover { fill: #D94A4A; }
</style>
<circle class="logo-circle" cx="60" cy="60" r="50" />
<text x="60" y="65" text-anchor="middle" fill="white" font-size="20" font-weight="bold">LOGO</text>
</svg>

2. Simple Bar Chart

<svg width="400" height="250">
<!-- Bars -->
<rect x="40" y="180" width="40" height="40" fill="#3498db" />
<rect x="100" y="140" width="40" height="80" fill="#2ecc71" />
<rect x="160" y="100" width="40" height="120" fill="#e74c3c" />
<rect x="220" y="60" width="40" height="160" fill="#f39c12" />
<rect x="280" y="120" width="40" height="100" fill="#9b59b6" />

<!-- Labels -->
<text x="60" y="235" text-anchor="middle" fill="#333">Jan</text>
<text x="120" y="235" text-anchor="middle" fill="#333">Feb</text>
<text x="180" y="235" text-anchor="middle" fill="#333">Mar</text>
<text x="240" y="235" text-anchor="middle" fill="#333">Apr</text>
<text x="300" y="235" text-anchor="middle" fill="#333">May</text>
</svg>

3. Animated Loading Spinner

<svg width="50" height="50" viewBox="0 0 50 50">
<style>
@keyframes spin { 100% { transform: rotate(360deg); } }
.spinner { animation: spin 1s linear infinite; transform-origin: 25px 25px; }
</style>
<circle class="spinner" cx="25" cy="25" r="20" fill="none" stroke="#3498db" stroke-width="4" stroke-dasharray="80" stroke-linecap="round" />
</svg>

4. Responsive SVG Graphic

<svg viewBox="0 0 200 200" style="width: 100%; max-width: 400px; height: auto;">
<!-- viewBox makes it scale to any container width -->
<circle cx="100" cy="100" r="90" fill="#f0f0f0" stroke="#ccc" stroke-width="2" />
<circle cx="100" cy="100" r="60" fill="#3498db" opacity="0.3" />
<circle cx="100" cy="100" r="30" fill="#e74c3c" />
</svg>

💡 Pro tip: The viewBox attribute is the secret to responsive SVG. It defines the coordinate system, and the SVG will scale automatically to fit its container.


🛠️ Try It Yourself

Create a Simple SVG Illustration

Task: Create an SVG illustration of a house using basic shapes.

Requirements:

  1. A rectangle for the house body
  2. A polygon or <path> for the roof
  3. A rectangle for the door
  4. Small rectangles or circles for windows
  5. A sun in the sky (circle with rays)

Hint:

<svg width="400" height="350" viewBox="0 0 400 350">
<!-- Sky -->
<rect x="0" y="0" width="400" height="350" fill="#87CEEB" />

<!-- Grass -->
<rect x="0" y="250" width="400" height="100" fill="#4CAF50" />

<!-- House body -->
<!-- Add your house here -->

<!-- Roof -->
<!-- Add the roof here -->

<!-- Door -->
<!-- Add the door here -->

<!-- Windows -->
<!-- Add windows here -->

<!-- Sun -->
<!-- Add a sun here -->
</svg>

🔍 SVG Best Practices

✅ Do's:

  • Use viewBox — makes your SVGs responsive and scalable
  • Add meaningful <title> and <desc> — improves accessibility for screen readers
  • Optimize SVG files — use tools like SVGO to remove unnecessary metadata
  • Use external stylesheets — keeps SVG code clean and maintainable
  • Set width and height — prevents layout shifts during loading

❌ Don'ts:

  • Embed complex SVGs inline — large SVGs are better as external files
  • Use raster images inside SVG — defeats the purpose of vector graphics
  • Forget xmlns — always include the SVG namespace for proper rendering
  • Hard-code colors — use CSS variables for theming flexibility
  • Assume all SVG features work everywhere — test across browsers

📊 SVG File Size Comparison

Graphic TypePNG (approx)SVG (approx)Savings
Simple logo15–30 KB1–3 KB80–90%
Icon set (10 icons)50–100 KB4–10 KB85–90%
Illustration100–500 KB15–80 KB50–80%
Complex map500 KB–2 MB100–500 KB40–60%

🎓 Quick Quiz

Test Your Knowledge

Which SVG attribute makes the graphic responsive to any container size?

  • width
  • height
  • viewBox
  • xmlns

Explanation: viewBox defines the coordinate system and aspect ratio, allowing the SVG to scale automatically to fit its container.

Think About It

When would you choose Canvas over SVG?

Answer: Canvas is better for applications that need to redraw thousands of elements every frame — like games, video processing, or complex data visualizations with frequent updates. SVG works better for static graphics, interactive UI elements, and cases where accessibility matters.



💡 Mentor's Final Note: SVG is one of the most underrated tools in web development. Once you master basic shapes and the coordinate system, you can create everything from simple icons to complex illustrations — all with code. SVG graphics are lightweight, accessible, and look stunning on any device. Start experimenting today! 🚀


📚 Summary

You Learned:

  • What SVG is and how it differs from raster graphics
  • Basic SVG shapes — circle, rect, line, ellipse, polygon, path
  • The coordinate system — how positioning works in SVG
  • Inline SVG vs <img> SVG — when to use each approach
  • SVG vs Canvas — choosing the right tool for the job
  • Practical examples — icons, charts, animations, and responsive graphics

Key Takeaway:

SVG lets you create resolution-independent graphics using nothing but HTML-like code. It's the perfect tool for logos, icons, illustrations, and any graphic that needs to look great at any size.


Purpose: Complete guide to SVG graphics in HTML Practice Time: 25–35 minutes Next Lesson: Canvas Graphics