SVG is one of the most powerful and underused tools in a web developer's toolkit. Beyond simply replacing PNG icons, SVG enables interactive graphics, smooth animations and accessible data visualizations, all without a single external library.
Four ways to embed SVG in HTML
1. As an <img> tag
The simplest method. Use <img src="logo.svg" alt="Logo"> just like any other image. The SVG scales to the element's CSS dimensions and the browser handles caching. Limitation: you cannot target inner elements with CSS or JavaScript.
2. As a CSS background-image
Useful for decorative SVGs: background-image: url('pattern.svg'). Works well for repeating patterns and icons used via CSS. Same limitation, no DOM access.
3. Inline SVG
Paste the SVG markup directly into your HTML. This gives full CSS and JavaScript access to every element inside the SVG. You can change fill colors on hover, animate paths with GSAP, or make parts interactive. The trade-off is a larger HTML file and no browser caching of the SVG itself.
4. As an <object> or <embed> tag
Older approach, mostly replaced by inline SVG or <img>. Still useful when you need an isolated SVG with its own CSS scope.
Styling SVG with CSS
Inline SVGs inherit CSS from the parent document. You can target SVG elements with normal CSS selectors: svg path { fill: #4f46e5; } or apply transitions: svg circle { transition: r 0.3s; }. Presentational attributes in the SVG (fill="red") are overridden by CSS, so it is good practice to remove them from production SVGs and apply all styling via CSS.
Animating SVG
- CSS transitions and @keyframes: animate fill, stroke, opacity, transform
- CSS stroke-dasharray / stroke-dashoffset: the classic 'drawing' line animation
- SMIL (built-in SVG animation): works without JavaScript, good for simple loops
- JavaScript (GSAP, anime.js): complex timelines, scroll-triggered animations
Optimizing SVG for production
SVGs exported from design tools often contain unnecessary metadata, editor-specific attributes and redundant path data. Run your SVGs through SVGO (available as a CLI, Vite plugin or online tool) before shipping to production. A typical SVGO pass reduces file size by 30–70% without any visible quality difference.
Accessibility
- Add <title> as the first child of <svg> for screen reader support
- Add aria-label and role="img" on the <svg> element for decorative icons use aria-hidden="true"
- Ensure sufficient color contrast in SVG illustrations
Ready to convert your image?
Free, no account required. PNG, JPG, WEBP, GIF, AVIF, TIFF and BMP supported.
Convert now, it's free