SVG in HTML
An inline <svg> element can live directly inside an HTML page, where viewBox and width/height together control exactly how it scales.
Embedding SVG Inline
Instead of loading an SVG as an external image with <img src="icon.svg">, you can paste the <svg>...</svg> markup directly into an HTML document. Inline SVG becomes part of the page's DOM, which means every shape inside it can be selected with CSS, targeted with JavaScript, and updated in real time, something a plain image file cannot do.
The viewBox Attribute
The viewBox attribute defines an internal coordinate system for the artwork, written as four numbers: 'min-x min-y width height'. Every shape inside the SVG is positioned using this internal coordinate system, completely independent of the pixel size the SVG is actually displayed at on the page.
- If both width/height and viewBox are set, the browser scales the viewBox content to fit the given width/height
- If viewBox is set but width/height are omitted, the SVG scales to fill its container like a block-level element
- Omitting viewBox entirely makes one unit in the markup equal one pixel on screen
- preserveAspectRatio defaults to 'xMidYMid meet', which keeps the aspect ratio and centers the content
- A mismatched viewBox and width/height aspect ratio can stretch or squash the artwork unless handled explicitly
Width, Height, and Responsive Scaling
To make an SVG responsive, set a viewBox but leave width and height unset (or set width to 100% in CSS and skip height). The browser then treats the SVG like any other block element, letting it grow or shrink with its parent container while viewBox preserves the internal proportions of the drawing.
Example
<!doctype html>
<html>
<body>
<h1>Inline SVG</h1>
<svg xmlns='http://www.w3.org/2000/svg' width='150' height='150'>
<rect x='10' y='10' width='130' height='130' fill='#16a34a' />
</svg>
</body>
</html>Example
<!DOCTYPE html>
<html>
<body>
<svg xmlns='http://www.w3.org/2000/svg' width='300' height='150' viewBox='0 0 100 50'>
<rect x='0' y='0' width='100' height='50' fill='#e2e8f0' />
<circle cx='50' cy='25' r='20' fill='#db2777' />
</svg>
</body>
</html>Example
<!DOCTYPE html>
<html>
<body>
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 200 100' style='width: 100%; height: auto;'>
<rect x='0' y='0' width='200' height='100' fill='#1e293b' />
<circle cx='100' cy='50' r='35' fill='#38bdf8' />
</svg>
</body>
</html>Exercise: SVG in HTML
How can SVG markup be placed directly inside a web page?