Inline SVG Graphics
Overview
SVG (Scalable Vector Graphics) is an image format written entirely in code. Unlike a JPG or PNG (which are grids of colored pixels that get blurry if you zoom in), an SVG is a set of mathematical instructions (e.g., 'draw a red circle here').
Because of this, SVGs are infinitely scalable. You can make an SVG the size of a billboard, and it will remain perfectly crisp. Even better, you can copy-paste SVG code directly into your HTML and animate it with CSS!
Syntax
You can write XML-like code directly in your HTML file to draw shapes. Here, we draw a circle. You can change its color instantly by changing the `fill` attribute.
<!-- An inline SVG defining a 100x100 canvas -->
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
<!-- cx, cy = center coordinates. r = radius -->
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>The true superpower of inline SVGs is that you can assign classes to the shapes and change their colors using CSS! If you load an SVG using an `<img>` tag, you CANNOT change its colors with CSS. You must write it inline to do this.
<!-- HTML -->
<svg width="50" height="50">
<rect class="my-box" width="50" height="50" />
</svg>
<!-- CSS -->
<style>
/* Notice we use 'fill' instead of 'background-color' */
.my-box {
fill: blue;
}
/* The box turns green when hovered! */
.my-box:hover {
fill: green;
}
</style>Common Pitfalls
- SVG code can be extremely long and messy (often hundreds of lines of `<path>` data). Don't try to write complex SVGs by hand. Use design tools like Figma or Adobe Illustrator, then export the code.
Real-World Example
Using an inline SVG for an interactive 'Like' heart button:
<button class="like-button">
<!-- viewBox defines the internal coordinate system -->
<svg viewBox="0 0 24 24" width="24" height="24">
<path
d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"
fill="transparent"
stroke="gray"
class="heart-icon"
/>
</svg>
</button>
<style>
/* When clicked, a JS class '.liked' could turn the heart red! */
.liked .heart-icon {
fill: red;
stroke: red;
}
</style>