Lesson 5 of 7
SVG in HTML
SVG (Scalable Vector Graphics) is a vector image format that uses XML to describe shapes, paths, and text. Unlike raster images (JPEG, PNG), SVGs scale to any size without losing quality - perfect for logos, icons, illustrations, and charts. SVGs can be embedded directly in HTML (inline SVG), referenced as image files, or used as CSS backgrounds. Inline SVGs can be styled with CSS and manipulated with JavaScript, making them incredibly powerful.
SVG Basics
SVG stands for Scalable Vector Graphics. Instead of storing pixels like JPEG/PNG, SVG describes shapes mathematically - a circle is stored as 'center point + radius', not thousands of individual pixels.
Two ways to use SVG in HTML:
1. Inline SVG - Paste the SVG code directly in HTML:
<svg width='100' height='100'>...</svg>
Pros: Can be styled with CSS, manipulated with JS, no extra HTTP request.
Cons: Adds to HTML file size, not cached separately.
2. SVG as image - Reference like any other image:
<img src='icon.svg' alt='Settings icon'>
Pros: Cached by browser, clean HTML.
Cons: Cannot style with CSS or manipulate with JS.
Basic SVG shapes:
• <rect> - Rectangle: x, y, width, height, rx (rounded corners)
• <circle> - Circle: cx, cy (center), r (radius)
• <ellipse> - Ellipse: cx, cy, rx, ry
• <line> - Line: x1, y1, x2, y2
• <polygon> - Closed shape: points="x1,y1 x2,y2 x3,y3"
• <path> - Complex shapes using drawing commands (M, L, C, Z)
• <text> - Text inside SVG: x, y position
Canvas excels at pixel rendering and games; SVG excels at crisp scalable icons and charts
SVG Example
<!DOCTYPE html>
<html>
<body>
<h1>SVG in HTML</h1>
<!-- Inline SVG: fully styleable -->
<svg width="200" height="200" viewBox="0 0 200 200">
<circle cx="100" cy="100" r="80" fill="#E44D26" />
<text x="100" y="110" text-anchor="middle" fill="white" font-size="24" font-weight="bold">HTML5</text>
</svg>
<!-- SVG shapes -->
<svg width="300" height="100">
<rect x="5" y="5" width="80" height="80" rx="10" fill="#229c6b" />
<circle cx="150" cy="45" r="40" fill="#2196F3" />
<polygon points="250,5 290,85 210,85" fill="#FF9800" />
</svg>
<!-- SVG as image (cannot style with CSS) -->
<!-- <img src="logo.svg" alt="Company logo" width="100"> -->
</body>
</html>Quick Quiz: SVG
Finished this lesson?