SVG Introduction

Beginner
⏱️ ~15 min
📚 Updated: Aug 2026
🎯 5 Examples
🚀 5 Try-it labs
vector · XML · CSS

What You’ll Learn

This page is a self-contained introduction to SVG (Scalable Vector Graphics)—sharp, resolution-independent graphics for the web. You will understand what SVG is, how to write basic shapes, how to style them, how SVG compares to Canvas and PNG, and where to go next in the topic index.

What is SVG

Vector basics

Learn how XML-based vector markup stays sharp at any size.

Structure

<svg> root

Write a minimal inline SVG with shapes, fill, and stroke.

Elements

Shapes & path

Meet rect, circle, ellipse, line, polyline, polygon, path, and text.

Compare

SVG vs others

Choose SVG, Canvas, or PNG/JPEG for the right job.

Examples

Hands-on labs

Practice five snippets with View Output and Try It Yourself.

Topic Index

Full roadmap

Jump from basic shapes to styling, effects, and advanced SVG.

Introduction

Scalable Vector Graphics (SVG) is an XML-based markup language for describing two-dimensional vector graphics. As a web standard maintained by the W3C, SVG is supported by all major modern browsers.

Unlike raster images (JPEG, PNG, GIF), SVG graphics are defined by math—lines, curves, and fills—so they scale to any size without losing quality. That makes SVG ideal for icons, logos, charts, diagrams, and responsive interfaces.

Because SVG is part of the DOM when inlined, you can target elements with CSS, attach event listeners with JavaScript, and animate properties—something raster images cannot do as flexibly.

Why it matters?

Modern UIs rely on crisp icons, logos, and diagrams on every screen size. SVG gives you resolution independence, small files for flat graphics, CSS theming, and scriptable interactivity in one format.

Key Highlights

Scalability

Scale up or down without pixelation—perfect for responsive and retina layouts.

Style Control

Style with CSS: fills, strokes, filters, transitions, and currentColor.

Interactivity

Elements support clicks, hovers, and scripting when SVG is inlined in HTML.

Accessibility

Add <title> and <desc> so meaningful graphics work with screen readers.

In short: SVG is text-based vector markup. Embed it inline or as a file, use viewBox for responsive scaling, and paint shapes with fill and stroke.

📝 Basic Structure

An SVG document is XML. Here is a minimal inline example in HTML—a red circle with a dark stroke:

index.html
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
Try It Yourself

Explanation

PieceRole
<svg>Root element; sets canvas size and the SVG namespace
cx, cyCenter coordinates of the circle
rRadius
stroke / stroke-widthBorder color and thickness
fillInterior color

🖌️ Common SVG Elements

Here are the most commonly used SVG shape elements. Each links to its dedicated tutorial:

ElementDescriptionTutorial
<rect>Rectangle (optionally rounded with rx/ry)Rectangle
<circle>Circle defined by center and radiusCircle
<ellipse>Oval with two radiiEllipse
<line>Straight line between two pointsLine
<polyline>Series of connected straight segments (open path)Polyline
<polygon>Closed shape with multiple sidesPolygon
<path>Complex shapes via path commands (most flexible)Path
<text>Accessible text labels inside the graphicText

Start with SVG Rectangle—the first basic shape in the sidebar—then explore the rest.

⚡ Quick Reference

TaskExample
Root canvas<svg width="200" height="200" viewBox="0 0 200 200">
Red circle<circle cx="50" cy="50" r="40" fill="red" />
Blue rectangle<rect x="10" y="10" width="80" height="40" fill="blue" />
Line<line x1="0" y1="0" x2="100" y2="100" stroke="black" />
Group shapes<g transform="translate(10,10)">...</g>
CSS themefill="currentColor" or CSS svg .icon { fill: ... }
Responsive iconviewBox="0 0 24 24" + CSS width/height

📋 SVG vs Canvas vs PNG/JPEG

All can display graphics, but they solve different problems.

SVG
vector markup

Best for icons, logos, diagrams, and UI illustrations that must stay sharp and styleable.

Canvas
bitmap surface

Best for games, dense charts, and pixel effects drawn with JavaScript. Scales cleanly only if redrawn.

PNG / JPEG
raster image

Best for photos, textures, and complex imagery on a fixed pixel grid.

Learn more in the Canvas Introduction when you need JavaScript pixel drawing.

Context

When to Use SVG

Reach for SVG whenever your graphic must scale, theme, or stay editable as markup.

  1. Icons & logos

    Flat brand marks and UI icons stay crisp on every density and theme.

  2. Charts & diagrams

    Lines, nodes, and labels remain selectable and styleable in the DOM.

  3. Illustrations & UI chrome

    Hero accents, empty states, and decorative shapes that need CSS control.

  4. Responsive graphics

    One viewBox drawing scales cleanly with CSS width and height.

  5. Not for photos

    Detailed photographs and noisy textures belong in WebP, JPEG, or PNG.

Key benefit: one text-based asset can scale, theme, animate, and remain searchable—without exporting a dozen PNG sizes.

📚 SVG Topic Index

Browse every SVG tutorial on CodeToFun, grouped by learning path. Start with Rectangle.

Basic Shapes

Styling & Effects

Advanced

Examples Gallery

Five starter snippets. Use View Output to preview here, or open Try It Yourself to edit and run live (?tryit=1 through 5).

📚 Getting Started

Start with a filled circle and a rounded rectangle, then try polygons and CSS.

Example 1 — Red circle with stroke

A classic filled circle with a dark outline using presentation attributes.

index.html
<svg width="120" height="120" xmlns="http://www.w3.org/2000/svg">
  <circle cx="60" cy="60" r="45"
          fill="#ef4444" stroke="#1e293b" stroke-width="4" />
</svg>
Try It Yourself

How It Works

The browser places the circle center at (60, 60) with radius 45. fill paints the interior; stroke and stroke-width draw the border.

Example 2 — Rounded rectangle

Use rx to soften corners into a card-like shape.

index.html
<svg width="140" height="80" xmlns="http://www.w3.org/2000/svg">
  <rect x="10" y="10" width="120" height="60" rx="12"
        fill="#3b82f6" />
</svg>
Try It Yourself

How It Works

x and y set the top-left corner; width and height set size. rx="12" rounds the corners. Continue in the Rectangle tutorial.

Example 3 — Star with polygon

A closed multi-point star built from a list of points.

index.html
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  <polygon points="50,5 61,38 95,38 68,59 79,91 50,71 21,91 32,59 5,38 39,38"
           fill="#fbbf24" stroke="#b45309" stroke-width="2" />
</svg>
Try It Yourself

How It Works

<polygon> connects the listed points and closes the shape automatically. Learn more in the Polygon tutorial.

Example 4 — CSS hover styled circle

Inline SVG can use CSS classes and transitions for interactive styling.

index.html
<style>
  .btn-icon { fill: #64748b; transition: fill 0.2s; cursor: pointer; }
  .btn-icon:hover { fill: #2563eb; }
</style>
<svg width="48" height="48" xmlns="http://www.w3.org/2000/svg">
  <circle class="btn-icon" cx="24" cy="24" r="20" />
</svg>
Try It Yourself

How It Works

The circle uses the CSS class .btn-icon for fill instead of a presentation attribute. External stylesheets can target inline SVG the same way. Hover in the preview or Try It editor to see the transition.

Example 5 — Responsive viewBox icon

Define geometry once with viewBox, then size the SVG with CSS or attributes.

index.html
<svg viewBox="0 0 24 24" width="48" height="48"
     xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
  <path fill="currentColor"
        d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 22 12 18.56 5.82 22
           7 14.14l-5-4.87 6.91-1.01L12 2z" />
</svg>
Try It Yourself

How It Works

viewBox="0 0 24 24" maps the path coordinates to a flexible viewport. Change width/height (or CSS size); proportions stay correct. currentColor lets the icon inherit text color.

Use Cases

Real-world places where SVG shows up every day on the web.

1. UI Icons

Navigation, buttons, and status indicators that must theme with CSS.

Example: a hamburger menu or checkmark icon.

2. Brand Logos

Wordmarks and symbols that stay sharp on retina screens.

Example: a site header logo that scales from mobile to desktop.

3. Charts & Data Viz

Bars, lines, and pie slices as selectable DOM elements.

Example: a sparklines dashboard widget.

4. Diagrams

Flowcharts, architecture maps, and annotated sketches.

Example: a deploy pipeline illustration.

5. Empty States

Friendly illustrations when a list or inbox has no data yet.

Example: a “no results” graphic in search UI.

6. Favicons & App Marks

Tiny marks that remain readable when scaled down.

Example: an SVG favicon that replaces multiple PNG sizes.

Pro Tip: if the graphic is mostly flat shapes and text, SVG usually beats a raster export for size, quality, and theming.

Advantages

Why SVG is an excellent choice for modern web graphics.

  1. 1. Resolution Independence

    Vector graphics look sharp on retina displays and when zoomed.

  2. 2. Styling & Scripting

    Customize with CSS and JavaScript for themes and interactions.

  3. 3. Compact File Size

    Often smaller than bitmaps for icons and simple illustrations; caching works like any static asset.

  4. 4. SEO Friendly

    Text inside SVG can be indexed; use meaningful labels where appropriate.

  5. 5. Accessibility Hooks

    Add <title> and <desc>, or mark decorative icons with aria-hidden.

Pro Tip: version-control SVG like code—because source is text, icon changes show up cleanly in Git diffs.

Usage Tips

Follow these practices for clean, scalable SVG on the web.

  1. 1. Prefer viewBox for responsive icons

    Define geometry once, then size with CSS width/height instead of fixed pixels alone.

  2. 2. Style with CSS when you need themes

    Classes, <style> blocks, or currentColor keep icons adaptable to dark mode and brand palettes.

  3. 3. Choose the right embed method

    Inline for CSS/JS control; <img> for simple cacheable icons; CSS background for decorative chrome.

  4. 4. Add accessible names when graphics matter

    Use <title>/<desc> for meaningful art; set aria-hidden="true" on pure decoration.

  5. 5. Optimize before production

    Simplify paths and strip unused metadata (tools like SVGOMG) so files stay small.

Pro Tip: know basic HTML first—SVG can live inline in an HTML file or as a separate .svg linked with <img>.

Common Pitfalls

Avoid these mistakes when SVG does not look or behave as expected.

  1. 1. Fixed pixels without a viewBox

    Hard-coded width/height alone can break responsive layouts.

    → Add a viewBox and size the SVG with CSS.

  2. 2. Expecting CSS control on <img> SVG

    External SVG loaded via <img> does not expose internals to page CSS or JS.

    → Inline the SVG (or use CSS filters on the image) when you need per-shape styling.

  3. 3. Huge unoptimized exports

    Design tools often leave metadata, unused groups, and noisy paths.

    → Optimize with SVGOMG (or similar) and enable gzip/brotli on the server.

  4. 4. Using SVG for photographs

    Complex photos become enormous as vectors or look wrong as traces.

    → Use WebP or JPEG for photos; keep SVG for flat graphics.

  5. 5. Inlining untrusted SVG

    Untrusted markup can embed scripts and create XSS risk.

    → Sanitize or serve untrusted SVG as <img>, never raw inline from unknown sources.

Pro Tip: if a shape vanishes, check fill/stroke visibility, coordinates inside the viewBox, and whether zero width/height/radius was set.

🔗 Ways to Use SVG on a Web Page

MethodHowBest when
Inline SVGPaste <svg>...</svg> in HTMLYou need CSS/JS control of individual shapes
<img><img src="icon.svg" alt="">Simple, cacheable icons without script access
CSS backgroundbackground-image: url(icon.svg)Decorative chrome that should not affect layout semantics
<object> / <embed>Legacy embedding optionsRare today; prefer inline or <img>

For responsive icons, add viewBox="0 0 100 100" and size with CSS width/height.

🧠 How SVG Renders in the Browser

1

Parse markup

The browser reads SVG XML (inline or loaded) and builds shape nodes in the DOM.

DOM
2

Apply styles

CSS and presentation attributes set fill, stroke, opacity, and transforms.

Style
3

Rasterize vectors

The engine converts paths to pixels at the current zoom level and device pixel ratio.

Render
=

Crisp graphics displayed

Shapes appear on screen; resize the page and vectors stay sharp.

Important Notes

  • SVG is XML-based vector markup supported by all modern browsers.
  • SVG origin is the top-left; positive y goes down.
  • fill paints the inside; stroke paints the border. CSS can override presentation attributes on inline SVG.
  • Prefer viewBox for responsive icons and illustrations.
  • SVG supports SMIL <animate>, but for new projects prefer CSS transitions/keyframes or JavaScript—they have broader tooling support.
  • Next step: draw your first box shape in the SVG Rectangle tutorial.

Quick Takeaway: write shapes in an <svg>, paint with fill/stroke, scale with viewBox, and pick the embed method that matches how much control you need.

Browser Support

SVG is a W3C web standard supported in all modern browsers — and has been for many years — for inline graphics and external .svg files.

SVG 1.1+

SVG

Use SVG inline or as .svg assets. Basic shapes, viewBox, fill, stroke, and CSS styling work consistently across Chrome, Firefox, Safari, Edge, and mobile browsers.

100% Modern browsers
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
SVG Universal

Bottom line: Safe for production sites. Prefer inline SVG or cached .svg assets; no polyfill is required for current browsers.

Wrap Up

🎉 Conclusion

SVG is a versatile, powerful format for creating web graphics. Its scalability, performance benefits, and ease of styling make it a great choice for modern web design.

By understanding the basics of SVG and how to use it, you can create high-quality, responsive graphics for your website—from favicons and icons to charts and hero illustrations.

Practice the five examples above, then continue to SVG Rectangle—the first basic shape in the sidebar.

Use shape elements, path, CSS, and viewBox for responsive icons. Compare with Canvas when you need pixel-drawn graphics.

💡 Best Practices

✅ Do

  • Add viewBox and size SVGs with CSS for responsiveness
  • Include <title> and <desc> for meaningful graphics
  • Simplify paths with tools like SVGOMG before production
  • Use currentColor so icons inherit text color from CSS
  • Set aria-hidden="true" on decorative icons
  • Optimize exported SVG from design tools (remove unused metadata)

❌ Don’t

  • Embed huge SVG illustrations without gzip/brotli compression
  • Rely on SMIL alone for critical animations in all browsers
  • Use SVG for detailed photographs—use WebP or JPEG instead
  • Forget accessible names on interactive SVG buttons
  • Hard-code pixel dimensions without a viewBox on responsive layouts
  • Inline untrusted SVG from unknown sources (XSS risk if scripts embedded)

Key Takeaways

Knowledge Unlocked

Five things to remember about SVG

Build crisp, scalable graphics the SVG way.

5
Core concepts
</> 02

<svg>

Root canvas for shapes

Structure
🎨 03

Fill & Stroke

Paint interiors and outlines

Style
🗺 04

viewBox

Responsive scaling

Layout
05

Next: Rectangle

First basic shape tutorial

Path

❓ Frequently Asked Questions

SVG (Scalable Vector Graphics) is an XML-based format for two-dimensional vector graphics. Shapes are defined mathematically, so they stay sharp at any size—unlike pixel-based PNG or JPEG images.
Often yes for simple icons and logos. SVG scales cleanly, stays small for flat graphics, and can be styled with CSS. PNG is better for photographs and complex raster artwork.
Yes. Paste an inline <svg> block in HTML, reference an external file with <img src="icon.svg">, or use SVG as a CSS background. Inline SVG allows CSS and JavaScript to target individual shapes.
SVG is DOM-based vector markup—each shape is an element you can style and click. Canvas is a bitmap drawing surface controlled by JavaScript pixels. SVG suits icons and diagrams; Canvas suits games and heavy animation.
All modern browsers support SVG. It is a W3C web standard. Very old browsers may need fallbacks, but SVG is safe for current projects.
Start with SVG Rectangle at /svg/rectangle—the first basic shape in the sidebar—then practice circle, ellipse, line, polygon, polyline, path, and text. After shapes, explore stroke, filters, patterns, gradients, interactivity, and links.

Did you Know? 🔊

Embed inline with <svg> in HTML or link an .svg file via <img>. Use viewBox for responsive scaling. Style shapes with fill, stroke, and CSS classes. SVG became a W3C recommendation in 2001—making it older than many JavaScript frameworks, yet still essential for modern UI icons. Because SVG source is text, you can version-control icon changes in Git like any code file.

Continue to SVG Rectangle

Learn the first basic shape in the sidebar—position, size, and rounded corners with <rect>.

Rectangle tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful