HTML Tutorial · HTML5 Features · Lesson 21 of 34
HTML Inline SVG
Draw scalable vector graphics with svg, use viewBox to scale them, and make them accessible.
What is SVG?
SVG (Scalable Vector Graphics) describes images as shapes. It stays sharp at any size, and you can put it directly in HTML. Every shape is an element, so you can style it with CSS, animate it and attach events.
<svg width="260" height="120" role="img" aria-label="A house in the sun">
<title>A house in the sun</title>
<circle cx="220" cy="30" r="20" fill="orange"></circle>
<rect x="40" y="55" width="90" height="55" fill="#a3e635" stroke="#365314"></rect>
<polygon points="30,55 85,15 140,55" fill="#b91c1c"></polygon>
<text x="150" y="105" font-size="14">Home</text>
</svg>
viewBox: drawing once, scaling anywhere
viewBox="0 0 100 100" defines the SVG's own coordinate system. The SVG can then be displayed at any size and the drawing scales to fit. Icons usually use a fixed viewBox and are sized with CSS.
<style>
.icon { width: 1.5em; height: 1.5em; fill: currentColor; vertical-align: middle; }
button { font-size: 18px; color: #4f46e5; }
button:hover { color: #be123c; }
</style>
<button>
<svg class="icon" viewBox="0 0 24 24" aria-hidden="true">
<path d="M12 21s-7-4.5-9.5-9A5.5 5.5 0 0 1 12 6a5.5 5.5 0 0 1 9.5 6C19 16.5 12 21 12 21z"></path>
</svg>
Save to favourites
</button>
Accessible SVG
- Meaningful graphics: add
role="img"andaria-label, or a<title>as the first child. - Decorative graphics: add
aria-hidden="true"so screen readers skip them.
SVG or img?
You can also load an .svg file with <img src="logo.svg" alt="...">. Use <img> when you just need to show it; use inline SVG when you want to style parts with CSS (fill: currentColor) or script it.
Test yourself
What does the viewBox attribute do?
It sets the SVG's background colourIt defines the SVG's internal coordinate system so the drawing scales to any displayed sizeIt crops the page around the SVGIt makes the SVG accessible
Show answer
Answer: It defines the SVG's internal coordinate system so the drawing scales to any displayed size
With a viewBox, the same drawing can be shown at 16px or 400px without losing sharpness.