HTML SVG
HTML SVG: Resolution-Independent Vector Graphics in Markup
SVG (Scalable Vector Graphics) defines crisp two-dimensional graphics using XML shapes such as circles, rectangles, polygons, and curved paths. Because SVGs describe math coordinates instead of fixed pixel grids, they stay razor-sharp at any zoom level or Retina display density.
Writing Inline SVG in HTML5
You can embed an svg element directly inside your HTML body without external image requests. Set a viewBox="0 0 width height" attribute so the coordinate system scales cleanly when resized with CSS width and height.
Because inline SVG shapes are real DOM nodes, CSS can style fill, stroke, and :hover transitions directly, and JavaScript can attach click events to individual paths.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML SVG Demo</title>
<style>
.badge-svg { width: 220px; height: 120px; }
.badge-svg rect:hover { fill: #1d4ed8; transition: fill 0.2s ease; }
</style>
</head>
<body>
<svg class="badge-svg" viewBox="0 0 220 120" role="img" aria-labelledby="svg-title">
<title id="svg-title">Verified Shield Badge</title>
<rect x="10" y="10" width="200" height="100" rx="14" fill="#2563eb" />
<circle cx="55" cy="60" r="24" fill="#38bdf8" />
<path d="M44 60 L52 68 L68 50" fill="none" stroke="#ffffff" stroke-width="5" stroke-linecap="round" stroke-linejoin="round" />
<text x="95" y="66" fill="#ffffff" font-family="system-ui, sans-serif" font-size="20" font-weight="bold">SVG5</text>
</svg>
</body>
</html>
Accessibility for SVG Graphics
Add role="img" and a nested title element (linked with aria-labelledby) for meaningful illustrations. For purely decorative icons placed beside visible button text, add aria-hidden="true" so screen readers do not announce duplicate graphics.
Common Mistakes to Avoid
- Omitting the
viewBoxattribute: WithoutviewBox, shrinking ansvgwith CSS clips the drawing instead of scaling it down proportionally. - Serving raw unoptimized exports from design tools: Run vector exports through SVGO to strip bloated editor metadata comments.
- Using SVG for complex photographs: Keep photos in WebP or JPEG; SVG excels at icons, logos, diagrams, and charts.
Frequently Asked Questions
Should I use inline svg or img src="icon.svg"?
Use inline svg when you want CSS hover colors (fill: currentColor) or animations, and use img when you want browser caching across many pages.
What does viewBox="0 0 24 24" mean?
It sets the internal drawing grid from (0, 0) to (24, 24) regardless of how large or small CSS displays the icon.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.