Codectionary / Developer documentation / HTML

<svg>

The <svg> element embeds Scalable Vector Graphics directly in HTML — vector-based images built from shapes, paths, and text rather than pixels, so they stay crisp at any size. Unlike canvas, SVG content is made of real DOM elements that can be styled with CSS and targeted with JavaScript individually, making it ideal for icons, logos, and interactive diagrams.

Syntax

<svg width="100" height="100">
  <circle cx="50" cy="50" r="40" fill="blue" />
</svg>

Examples

Basic Shapes

Drawing a circle and rectangle with SVG.

<svg width="200" height="100">
  <rect x="10" y="10" width="80" height="80" fill="#3b82f6" />
  <circle cx="150" cy="50" r="40" fill="#10b981" />
</svg>

Inline Icon

A simple checkmark icon built with an SVG path.

<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
  <path d="M20 6L9 17l-5-5" />
</svg>

Styling SVG with CSS

Applying CSS to individual SVG elements, including on hover.

<style>
  .icon-circle { fill: #6b7280; transition: fill 0.2s; }
  .icon-circle:hover { fill: #3b82f6; }
</style>
<svg width="60" height="60">
  <circle class="icon-circle" cx="30" cy="30" r="25" />
</svg>

Attributes

  • width (number): The rendered width of the SVG
  • height (number): The rendered height of the SVG
  • viewBox (string): Defines the internal coordinate system, enabling responsive scaling
  • fill (color): The fill color for shapes within the SVG

Best practices

  • Use viewBox so the SVG scales cleanly to any container size rather than being locked to fixed pixel dimensions
  • Prefer SVG over raster images (PNG/JPG) for icons and logos, since they stay sharp at any resolution and are typically smaller in file size
  • Add a title element inside the SVG and appropriate ARIA attributes for accessibility, especially for meaningful (non-decorative) graphics
  • Use CSS fill and stroke properties instead of hardcoding colors when the SVG needs to adapt to themes

At a glance

Purpose
Structure and meaning for web content
File extension
.html · .htm
Runs in
Web browsers
Usually used with
CSS and JavaScript

Specifications & further reading

Related HTML documentation