SVG Deep Dive
SVG (Scalable Vector Graphics) is an XML-based format for vector images. Unlike raster formats, SVG files contain text describing shapes, making them editable, styleable, and infinitely scalable. For icons, logos, and simple graphics on the web, SVG is often the best choice.
SVG Structure
An SVG file describes shapes using XML elements:
<svg width="100" height="100" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="blue" />
<rect x="10" y="10" width="30" height="30" fill="red" />
<path d="M 10 80 L 50 20 L 90 80 Z" fill="green" />
</svg>
The viewBox defines the coordinate system. Shapes position themselves within this system. The width and height set the display size, but the viewBox content scales to fit.
Common elements include:
circle— circles and ellipsesrect— rectangles and squarespath— complex shapes via drawing commandsline,polyline,polygon— lines and multi-point shapestext— text rendered as vectors
Using SVG on the Web
Inline SVG embeds directly in HTML:
<button>
<svg viewBox="0 0 24 24" width="24" height="24">
<path d="M12 2L2 7l10 5 10-5-10-5z"/>
</svg>
Save
</button>
Inline SVG can be styled with CSS and manipulated with JavaScript.
Image tag treats SVG like any image:
<img src="logo.svg" alt="Company logo">
Simple but loses styling and scripting capabilities.
CSS background works for decorative graphics:
.icon {
background-image: url('icon.svg');
}
Styling With CSS
Inline SVG responds to CSS, enabling dynamic styling:
svg {
fill: currentColor; /* Inherits text color */
width: 24px;
height: 24px;
}
svg:hover {
fill: blue;
}
.icon-large {
width: 48px;
height: 48px;
}
The currentColor value is particularly useful — icons automatically match surrounding text color.
Icon Systems
For applications with many icons, organize SVGs efficiently:
Symbol references define icons once and reuse them:
<!-- Define icons (often in a hidden container) -->
<svg style="display: none">
<symbol id="icon-star" viewBox="0 0 24 24">
<path d="..."/>
</symbol>
</svg>
<!-- Use icons anywhere -->
<svg><use href="#icon-star"/></svg>
This approach reduces duplication and enables consistent styling across your application.