HTML SVG Basics
SVG (Scalable Vector Graphics) is an XML-based language for describing two-dimensional vector graphics directly in HTML. Unlike Canvas (pixel-based, imperative), SVG graphics are part of the DOM — fully styleable with CSS, animatable, accessible to screen readers, and infinitely scalable without pixelation. In this chapter you'll master all core SVG elements, the path mini-language, gradients, transforms, CSS animations, and when to choose SVG over Canvas.
<rect>,
<circle>, <ellipse>,
<line>, <polygon>
<path> element and
its d-attribute command languagelinearGradient, radialGradient), and
<defs>
<g> group elementWhat is SVG and How to Embed It
SVG is written in XML markup — tags, attributes, and nesting — embedded directly in
HTML using the <svg> element. Every SVG element becomes a
real DOM node that you can select with CSS selectors, manipulate with JavaScript, and
animate with CSS transitions or @keyframes.
viewBox attribute defines the
internal coordinate system: viewBox="minX minY width height". The
SVG is drawn in this space, then scaled to fit the element's display size. This makes SVG
resolution-independent — a viewBox of 0 0 100 100
renders crisply at any display size from 50px to 5000px.
fill
(interior colour) and stroke (outline). Both accept any CSS colour
value. You can set them as XML attributes directly on the element, or via CSS — CSS always wins over
element attributes.<img src="icon.svg">) — simple, cacheable, no DOM access.
CSS background (background: url(icon.svg)) — for
decorative images only.
<!-- Inline SVG — part of the HTML DOM -->
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 200 100"
width="400"
height="200"
role="img"
aria-label="K2infocom logo"
>
<!-- shapes go here -->
<rect x="10" y="10" width="80" height="60"
fill="#e44d26" rx="8"/>
</svg>
<!-- External SVG as image (no DOM access) -->
<img src="logo.svg" alt="K2infocom logo" width="200">
SVG Shape Elements — Reference Cards
SVG provides eight dedicated shape elements. Each has its own set of attributes — there are no methods like Canvas. Everything is declarative XML:
rx and ry round the corners — set only rx
for uniform border-radius.rx, ry (corner radius)
cx/cy, size with r (radius).r (radius)
rx)
and vertical (ry) radii.rx (x-radius), ry (y-radius)
stroke — lines have no fill area to render.x2, y2 (end)
stroke-linecap
polyline is an open multi-segment line. polygon auto-closes the path — last point connects back to first. Both
take a points attribute.<div> for SVG elements.Inherits fill/stroke to children
<svg viewBox="0 0 500 200" xmlns="http://www.w3.org/2000/svg">
<!-- Rounded rectangle -->
<rect x="10" y="20" width="100" height="80"
rx="12" fill="#e44d26" stroke="#c0392b" stroke-width="2"/>
<!-- Circle -->
<circle cx="180" cy="60" r="50"
fill="#3b82f6" fill-opacity="0.85"/>
<!-- Ellipse -->
<ellipse cx="290" cy="60" rx="70" ry="40"
fill="none" stroke="#a855f7" stroke-width="3"/>
<!-- Line -->
<line x1="380" y1="10" x2="480" y2="110"
stroke="#22c55e" stroke-width="4" stroke-linecap="round"/>
<!-- Polygon (triangle — auto-closes) -->
<polygon points="60,140 10,190 110,190"
fill="#f59e0b" stroke="#d97706" stroke-width="1.5"/>
<!-- Polyline (open path) -->
<polyline points="160,190 180,140 200,170 220,120 240,180"
fill="none" stroke="#06b6d4" stroke-width="3"
stroke-linejoin="round"/>
</svg>
The <path> Element — SVG's Most
Powerful Shape
The <path> element can draw any
shape — including circles, custom curves, icons, and complex illustrations. All the shape
instructions are encoded in the d attribute using a compact command
language. Uppercase commands use absolute coordinates; lowercase use relative coordinates
(offset from the current point).
| Command | Name | Parameters | What it does |
|---|---|---|---|
| M / m | Move To | x y | Move the "pen" to (x, y) without drawing. Every path starts with M. |
| L / l | Line To | x y | Draw a straight line from the current point to (x, y). |
| H / h | Horizontal Line | x | Draw a horizontal line to absolute x (or relative dx). Shorthand for L x currentY. |
| V / v | Vertical Line | y | Draw a vertical line to absolute y (or relative dy). Shorthand for L currentX y. |
| C / c | Cubic Bézier | x1 y1, x2 y2, x y | Draw a cubic Bézier curve. Two control points (x1,y1) and (x2,y2), ending at (x,y). |
| Q / q | Quadratic Bézier | x1 y1, x y | Draw a quadratic Bézier curve. One control point (x1,y1), ending at (x,y). |
| A / a | Arc | rx ry x-rot large-arc sweep x y | Draw an elliptical arc between current point and (x,y). |
| Z / z | Close Path | — | Draw a straight line back to the first point in the current sub-path and close it. |
<!-- Triangle: M(start) L(line) L(line) Z(close) -->
<path
d="M 100 10
L 10 90
L 190 90
Z"
fill="#a855f7"
stroke="#7c3aed"
stroke-width="2"
/>
<!-- S-curve using cubic bezier -->
<!-- C cp1x,cp1y cp2x,cp2y endx,endy -->
<path
d="M 20 80
C 20 20, 100 20, 100 80
C 100 140, 180 140, 180 80"
fill="none"
stroke="#e44d26"
stroke-width="3"
/>
<!-- Simple icon arrow using H (horizontal) and V (vertical) -->
<path
d="M 10 50
H 80
L 60 30
M 80 50
L 60 70"
fill="none"
stroke="#22c55e"
stroke-width="3"
stroke-linecap="round"
stroke-linejoin="round"
/>
d attribute. Understanding the commands helps
you read, debug, and make minor edits to exported SVG code. Libraries like Heroicons,
Lucide, and Phosphor provide ready-made SVG icon paths for web projects.
Text in SVG
The <text> element renders scalable,
selectable, accessible text. Use <tspan> for inline formatting of
portions of the text. SVG text is real DOM text — searchable and accessible, unlike Canvas
text which is rasterised pixels.
<!-- Basic text -->
<text
x="50%"
y="50"
text-anchor="middle" <!-- start | middle | end -->
dominant-baseline="middle" <!-- aligns vertically -->
font-size="24"
font-family="Segoe UI, sans-serif"
font-weight="700"
fill="#e44d26"
>K2infocom</text>
<!-- tspan: inline formatting within text -->
<text x="20" y="90" font-size="18" fill="#f0f0e8">
Learn
<tspan fill="#3b82f6" font-weight="700">HTML</tspan>
and
<tspan fill="#a855f7" font-weight="700">SVG</tspan>
</text>
<!-- Text on a path -->
<defs>
<path id="curve" d="M 20 120 Q 200 40 380 120"/>
</defs>
<text font-size="16" fill="#f59e0b">
<textPath href="#curve">
K2infocom — Web Dev with SVG!
</textPath>
</text>
Gradients and <defs>
SVG gradients are defined inside <defs> — a
section for reusable definitions that aren't rendered themselves. Each gradient gets an id, then shapes reference it with fill="url(#gradientId)".
<svg viewBox="0 0 400 160" xmlns="http://www.w3.org/2000/svg">
<defs>
<!-- Linear gradient: left → right -->
<linearGradient id="btnGrad"
x1="0%" y1="0%"
x2="100%" y2="0%">
<stop offset="0%" stop-color="#e44d26"/>
<stop offset="100%" stop-color="#f59e0b"/>
</linearGradient>
<!-- Radial gradient: inner glow effect -->
<radialGradient id="glowGrad"
cx="40%" cy="35%"
r="60%">
<stop offset="0%" stop-color="#ffffff" stop-opacity="0.9"/>
<stop offset="100%" stop-color="#a855f7" stop-opacity="1"/>
</radialGradient>
</defs>
<!-- Use gradients via url(#id) -->
<rect x="10" y="20" width="160" height="60"
rx="10" fill="url(#btnGrad)"/>
<circle cx="300" cy="80" r="70"
fill="url(#glowGrad)"/>
</svg>
Transforms — translate, rotate, scale
The transform attribute applies geometric
transformations to any SVG element or group. Multiple transforms can be combined by listing them
space-separated — they are applied right-to-left.
<!-- translate(tx, ty) — move element -->
<rect x="0" y="0" width="60" height="40"
fill="#e44d26"
transform="translate(50, 30)"/>
<!-- rotate(angle, cx, cy) — rotate around point -->
<rect x="-30" y="-20" width="60" height="40"
fill="#3b82f6"
transform="translate(150,60) rotate(45)"/>
<!-- scale(sx, sy) — scale element -->
<circle cx="0" cy="0" r="20"
fill="#a855f7"
transform="translate(250,60) scale(2)"/>
<!-- Group: shared transform on all children -->
<g transform="translate(350,60) rotate(30)"
fill="#f59e0b" opacity="0.9">
<circle cx="0" cy="0" r="20"/>
<rect x="25" y="-10" width="30" height="20"/>
</g>
Animating SVG with CSS
Because inline SVG elements are part of the DOM, you can animate them with CSS
transitions and @keyframes — targeting SVG-specific
properties like fill, stroke, stroke-dashoffset, r (circle radius),
and transform.
<!-- Spinning shape -->
<rect x="-25" y="-25" width="50" height="50"
fill="#e44d26"
transform="translate(50,50)"
style="transform-origin: 0 0;
transform-box: fill-box;
animation: spin 2s linear infinite;"/>
<!-- Stroke draw-on effect (dasharray trick) -->
<path
d="M 10 50 Q 100 0 190 50"
fill="none"
stroke="#3b82f6"
stroke-width="3"
stroke-dasharray="200" <!-- total path length -->
stroke-dashoffset="200" <!-- start fully hidden -->
style="animation: drawStroke 2s ease forwards;"
/>
<style>
@keyframes spin {
to { transform: rotate(360deg); }
}
@keyframes drawStroke {
to { stroke-dashoffset: 0; } /* reveal stroke */
}
@keyframes pulse {
0%, 100% { r: 20px; }
50% { r: 32px; }
}
@keyframes colorCycle {
0% { fill: #e44d26; }
33% { fill: #a855f7; }
66% { fill: #22c55e; }
100% { fill: #e44d26; }
}
/* Hover effects on SVG via CSS */
circle:hover { opacity: 0.7; cursor: pointer; }
rect { transition: fill 0.3s; }
rect:hover { fill: #f06529; }
</style>
stroke-dasharray to the total path length and stroke-dashoffset to the same value (fully hidden). Then animate stroke-dashoffset to 0 — the stroke
appears to draw itself. Get exact path length with path.getTotalLength()
in JavaScript.
SVG vs Canvas — When to Use Which
Both SVG and Canvas render graphics in the browser, but they work very differently. Choosing the right one depends on your use case:
Common Mistakes — Do's & Don'ts
These are the most frequent SVG mistakes beginners make:
<!-- viewBox for resolution independence -->
<svg viewBox="0 0 100 100"
width="200" height="200">
<!-- crisp at any size -->
</svg>
<!-- Accessible inline SVG -->
<svg role="img"
aria-label="K2infocom logo">
<title>K2infocom logo</title>
...
</svg>
<!-- defs for reuse -->
<defs>
<linearGradient id="grad">...</linearGradient>
</defs>
<!-- No viewBox — fixed pixel size only -->
<svg width="200" height="200">
<!-- blurry at different display sizes -->
</svg>
<!-- No accessibility on icon SVG -->
<svg>
<!-- screen readers say "svg" with no context -->
<path d="M 10 10 ..."/>
</svg>
<!-- Duplicating gradient definitions -->
<rect fill="url(#grad)"/>
<circle fill="url(#grad2)"/>
<!-- Should use one gradient in <defs> -->
Try It Yourself
Edit the SVG demo below and click Open in Editor to see shapes, gradients, transforms, and CSS animations all running live in full screen.
onclick attribute
fires a JavaScript alert directly on the SVG element. Try changing the gradient colours in <stop stop-color>. Modify the star path's d attribute and watch the shape update instantly.
Quick Check — Chapter 20
Expand each question to check your understanding before moving on to the multiple choice quiz.
viewBox attribute defines the internal coordinate
space of an SVG — the virtual canvas that your shapes are drawn on. It takes four values:
minX minY width height. The SVG viewport (the element's actual
display size set by width/height
or CSS) is then stretched or shrunk to fit this coordinate space — automatically scaling all shapes
proportionally. This makes SVG resolution-independent: you draw a shape at viewBox="0 0 100 100" and it renders crisp at 50px, 500px, or 5000px
display size. Without viewBox, the SVG has no coordinate reference —
shapes may overflow or not scale as expected.
points attribute — a list of x,y coordinate
pairs separated by spaces. The difference is how the shape is closed. <polyline> draws connected line segments but leaves the
path open — the last point is not connected back to the first. <polygon> automatically closes the path by
drawing a straight line from the last point back to the first point. This means <polygon> always creates a closed, fillable shape, while <polyline> is an open line path — it can have a stroke but its
fill is unreliable (it fills the gap between start and end, which is usually not what you want).
stroke-dasharray defines the
dash pattern — setting it to the total length of the path creates one single dash
exactly as long as the entire path. stroke-dashoffset shifts where
the dash starts — setting it to the same total length hides the entire stroke (the dash is shifted
completely off the visible area). Animating stroke-dashoffset from
the total length down to 0 with CSS @keyframes gradually reveals the stroke — creating the "drawing on"
effect. Get the total length in JavaScript with pathElement.getTotalLength().
<img>, the browser treats it as an
external resource — it is isolated from the page's DOM. You cannot apply CSS classes to
internal shapes, cannot run JavaScript that interacts with the SVG elements, cannot change fill colour
with CSS variables, and cannot add hover/click event listeners to individual shapes. Inline SVG, on the
other hand, makes every <circle>, <rect>, and <path> a
real DOM node — selectable with querySelector, styleable with CSS,
animatable with CSS transitions and @keyframes, and interactive with
JavaScript event listeners. Use <img> for simple decorative
icons you don't need to interact with; use inline SVG for interactive, animated, or CSS-themed graphics.
<defs> is a container for reusable
definitions that are not rendered directly — they only render when referenced by other
elements. It is equivalent to defining CSS variables or a template. Common contents: <linearGradient> and <radialGradient> (referenced with fill="url(#id)"), <pattern>
(repeating tile fill), <clipPath> (masking shapes), <filter> (blur, shadow effects), <symbol> (reusable icon templates referenced with <use>), and <path>
definitions for <textPath>. Always put gradients and patterns
in <defs> rather than duplicating them on each element.
<defs id="myGrad"> on a shape's fill?<path> d attribute, what does the Z command
do?- SVG is XML-based vector graphics embedded inline in HTML. Every element is a DOM node —
styleable with CSS, interactive with JS, accessible to screen readers, and infinitely scalable. The
viewBoxattribute defines the coordinate space for resolution independence. - Shape elements:
<rect>(x, y, width, height, rx),<circle>(cx, cy, r),<ellipse>(cx, cy, rx, ry),<line>(x1, y1, x2, y2),<polyline>(open),<polygon>(auto-closes). Painted withfillandstroke. - The
<path>element draws any shape using thedattribute: M (move), L (line), H/V (horizontal/vertical), C (cubic Bézier), Q (quadratic Bézier), A (arc), Z (close). - Gradients go in
<defs>and are referenced withfill="url(#id)".<linearGradient>and<radialGradient>use<stop offset color>children. - Transforms:
translate(tx, ty),rotate(angle),scale(sx, sy)— applied via thetransformattribute. Use<g>to group elements and apply shared transforms. - CSS animations work on SVG — animate
fill,stroke,transform,stroke-dashoffset, andr. Choose SVG for icons, charts, and accessible UI graphics; Canvas for games, particle systems, and pixel manipulation.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions, and stay updated with new tutorials.