DevAcademy
LearnHTMLSVG Basics
AdvancedHTML

SVG Basics

Learn how to draw scalable vector graphics directly inline in HTML using the svg element and basic shape elements.

Reading Time

16 min

Lesson

Lesson 26 of 27

What is SVG?

SVG (Scalable Vector Graphics) is an XML-based format for drawing 2D graphics using shapes and paths instead of pixels. Because it’s vector-based, SVG stays crisp at any zoom level or screen resolution.

Inline SVG

<svg width="200" height="200" viewBox="0 0 200 200">
  <circle cx="100" cy="100" r="80" fill="steelblue" />
</svg>
Output

Basic Shape Elements

ElementDraws
<circle>A circle, using cx, cy, and r
<rect>A rectangle, using x, y, width, and height
<line>A straight line between two points
<polygon>A closed shape from a list of points
<path>Any complex shape using a drawing command string
<text>Text rendered as part of the graphic

Rectangle and Line

<svg width="200" height="100">
  <rect x="10" y="10" width="120" height="60" fill="orange" />
  <line x1="0" y1="0" x2="200" y2="100" stroke="black" stroke-width="2" />
</svg>
Output

The viewBox Attribute

viewBox defines the coordinate system of the SVG canvas independently of its displayed width and height, which is what allows SVG graphics to scale cleanly to any size.

Using an Inline SVG Icon

<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor">
  <path d="M12 2 L2 22 L22 22 Z" stroke-width="2" />
</svg>
Output

Inline SVG vs img

SVG can be embedded inline (as shown above), referenced via <img src="icon.svg">, or set as a CSS background-image. Inline SVG is the most flexible option since it can be styled with CSS and manipulated with JavaScript.

SVG Uses Its Own Attributes

SVG elements use attributes like fill, stroke, and stroke-width instead of CSS background-color and border — though many of these can also be controlled from CSS on inline SVG.

Best Practice

Use inline SVG for icons and graphics that need to change color or animate via CSS/JavaScript, and use <img> or CSS background-image for static illustrations to keep markup lean.

Interview Questions

Quick Quiz

1. What does SVG stand for?

2. Which attribute draws a circle in SVG?

3. What is the main advantage of inline SVG over <img src="icon.svg">?