Inline SVG
Overview
Scalable Vector Graphics (SVG) are mathematical formulas defining shapes, rather than grids of pixels (like JPG or PNG). Because they are math-based, they scale infinitely without ever getting pixelated or blurry, making them perfect for logos and UI icons. More importantly, because SVG files are literally just XML/HTML text, you can paste the code directly inline into your HTML document. This eliminates the HTTP request required to download an image file and allows you to manipulate the SVG shapes directly using standard CSS and JavaScript.
Syntax
<!--
Pasting SVG code directly into the HTML!
We can use standard CSS classes to style it.
-->
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
width="48"
height="48"
class="icon-heart"
>
<!-- We can change the color dynamically using the 'fill' attribute -->
<path
fill="currentColor"
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"
/>
</svg>Common Pitfalls
- Missing the
viewBoxattribute. Without theviewBox(which defines the internal coordinate system of the drawing), the SVG will not scale correctly when you attempt to change itswidthandheightvia CSS. - Pasting massive, unoptimized SVGs exported directly from Figma or Adobe Illustrator. These files contain thousands of lines of useless metadata and editor junk. Always run them through an optimizer like SVGOMG before pasting them into your HTML.
Interview Questions
fill="currentColor" a powerful trick for Inline SVGs?It commands the SVG to inherit its fill color from the parent element's CSS color property. This allows you to easily change the icon's color on hover or in Dark Mode just by changing text color on the parent button or div.
Real-World Example
A highly dynamic icon component in React utilizing Inline SVGs.
// Because it's inline, React can control the SVG perfectly!
const CheckIcon = ({ className }) => (
<svg
className={`w-6 h-6 ${className}`}
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
);Check Your Knowledge
Test your understanding of Inline SVG with these quick questions.