HTML & CSSMedium
What is <svg>?
SVG (Scalable Vector Graphics) is an XML-based format for vector images that you can write inline in HTML with <svg>. Shapes are described mathematically, so they stay crisp at any size, and because each shape is a DOM element, SVG can be styled with CSS, animated, scripted and made accessible.
Core building blocks
viewBox="0 0 24 24": the internal coordinate system; combined with CSS width/height it makes the graphic scale.- Shapes:
<rect>,<circle>,<line>,<polyline>,<polygon>, and the powerful<path d="...">. <g>groups elements;<defs>+<use>reuse them;<symbol>builds icon sprites.<text>renders real, selectable text.- Gradients, masks, clip paths and filters.
Ways to use SVG
- Inline
<svg>: full CSS/JS control,fill="currentColor"inherits text color (perfect for icons). <img src="logo.svg">: cached, simple, but no styling from the page.- CSS
background-image: decorative only.
Accessibility
- Meaningful graphic:
role="img"plusaria-labelledbypointing at a<title>inside the SVG. - Decorative icon:
aria-hidden="true"(and give the button its own label).
When to choose SVG
Icons, logos, illustrations, simple charts and anything that must scale. For tens of thousands of moving points, prefer <canvas>.
Security
SVG files can contain scripts; sanitize user-uploaded SVGs before inlining them.
Code example
html
1<style>2 .icon { width: 48px; height: 48px; color: #2b4bff; transition: color .2s, transform .2s; }3 button:hover .icon { color: #e11d48; transform: rotate(-10deg) scale(1.1); }4 button { display: inline-flex; align-items: center; gap: 8px; font: 600 16px system-ui; padding: 8px 14px; }5</style>67<button type="button">8 <svg class="icon" viewBox="0 0 24 24" aria-hidden="true">9 <path fill="currentColor" d="M12 21s-7.5-4.6-9.6-9.2C.9 8.4 3 4.5 6.7 4.5c2.1 0 3.6 1.2 5.3 3.1 1.7-1.9 3.2-3.1 5.3-3.1 3.7 0 5.8 3.9 4.3 7.3C19.5 16.4 12 21 12 21z"/>10 </svg>11 Add to favorites12</button>1314<svg viewBox="0 0 200 80" width="300" role="img" aria-labelledby="chartTitle">15 <title id="chartTitle">Weekly visits rising from 20 to 70</title>16 <polyline points="10,70 50,55 90,60 130,35 170,20" fill="none" stroke="#0b1020" stroke-width="3"/>17 <circle cx="170" cy="20" r="5" fill="#ffd84d" stroke="#0b1020" stroke-width="2"/>18</svg>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.