Seven Practical Approaches for Using SVG in Frontend Development
Browsers can render SVG directly when served as a standalone XML file. Define the root element with proper namespace declaration so the engine knows how to parse it.
<?xml version="1.0" encoding="UTF-8"?>
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
<title>Hello</title>
<circle cx="50" cy="50" r="50" fill="#ff69b4" />
</svg>
Embedding SVG inline within HTML leverages the browser's native parsing of SVG elements when using an HTML5 doctype. Namespace declaration is optional except for children of <foreignObject>. This method enables direct styling and scripting on SVG nodes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inline SVG Demo</title>
</head>
<body>
<section>
<svg width="100%" height="100%">
<rect x="10" y="10" width="80" height="80" fill="#ff69b4" />
</svg>
</section>
</body>
</html>
Using SVG as a CSS bcakground image treats it like any raster asset. The vector nature allows scaling without quality loss.
<style>
.bg-svg {
width: 120px;
height: 120px;
background-image: url('shape.svg');
background-repeat: no-repeat;
background-size: contain;
}
</style>
<div class="bg-svg"></div>
The <img> element can reference an SVG file path, making it simple to swap graphics while keeping markup concise.
<img src="icon.svg" alt="Icon" width="100" height="100" />
An <iframe> can load an SVG document as a nested browsing context. Browsers render the file but may apply default borders that require CSS overrides.
<iframe src="graphic.svg" width="150" height="150"></iframe>
The <embed> tag acts as a container for external resources, including SVG. It lacks falback content, so embedding failures leave no alternative representation.
<embed src="illustration.svg" width="150" height="150" />
With <object>, SVG is embedded via its data attribute and declared with MIME type. Older browsers with SVG plugins could render it; modern engines handle it natively without extra attributes.
<object data="diagram.svg" type="image/svg+xml" width="150" height="150"></object>