SVG Basics for Developers
A practical introduction to SVG for developers covering shapes, paths, viewBox, styling, responsive graphics, accessibility, embedding, and optimization.
SVG, or Scalable Vector Graphics, is an XML-based image format designed for describing two-dimensional graphics. Unlike raster formats such as PNG and JPEG, SVG describes shapes, paths, text, colors, and other graphical elements as structured data that browsers can render at any resolution.
For web developers, SVG is especially useful for icons, logos, illustrations, diagrams, charts, interface graphics, and other visual elements that need to remain sharp at different sizes. Because SVG is part of the web platform, it can also be styled with CSS and manipulated with JavaScript.
This guide introduces the core SVG concepts developers need to understand: the SVG document structure, basic shapes, paths, coordinates, viewBox, styling, responsive sizing, embedding methods, accessibility, and optimization.
What Is SVG?
SVG stands for Scalable Vector Graphics. It is a vector graphics format standardized by the W3C and supported directly by modern web browsers.
The key difference between vector and raster graphics is how the image is represented. A raster image consists of pixels. An SVG describes graphical objects using mathematical coordinates and instructions, allowing the browser to calculate how those objects should be rendered.
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" fill="blue" />
</svg>The example creates a blue circle inside a 100 by 100 SVG coordinate system. The browser renders the circle based on its center coordinates and radius rather than storing a fixed collection of pixels.
Why Developers Use SVG
SVG is particularly valuable when graphics need to scale without becoming blurry. A single SVG can be displayed as a small icon, a large logo, or part of a high-resolution interface without requiring a separate image for every display size.
- Vector graphics remain sharp when scaled.
- SVG files can often be much smaller than equivalent raster images for simple graphics.
- SVG elements can be styled with CSS.
- SVG can be manipulated with JavaScript.
- SVG can contain accessible text and metadata.
- SVG works naturally with responsive web layouts.
- SVG supports animation and interaction.
- SVG can be embedded directly into HTML.
SVG is not automatically smaller or better than raster formats. Photographs and highly detailed textures are usually more appropriate for raster formats such as JPEG, WebP, or AVIF. SVG is strongest when the image consists of geometric shapes, paths, text, or other structured vector content.
The Basic SVG Document
An SVG document can be extremely small. At minimum, an SVG root element defines the SVG namespace and contains one or more graphical elements.
<svg xmlns="http://www.w3.org/2000/svg">
<rect width="100" height="50" fill="tomato" />
</svg>The xmlns attribute identifies the SVG XML namespace. When SVG is written inline inside an HTML document, the namespace is often optional in practice, but including it is conventional and important for standalone SVG documents.
The SVG Coordinate System
SVG uses a coordinate system to position graphical elements. By default, the origin is at the top-left of the SVG viewport. The x coordinate increases toward the right, while the y coordinate increases downward.
<svg viewBox="0 0 200 100">
<circle cx="50" cy="50" r="20" />
<circle cx="150" cy="50" r="20" />
</svg>Here, the coordinate system is 200 units wide and 100 units high. The first circle is centered at x=50 and y=50, while the second is centered at x=150 and y=50.
The viewBox Attribute
The viewBox attribute is one of the most important SVG concepts for web developers. It defines the internal coordinate system that SVG content uses and allows the browser to scale that coordinate system into the rendered viewport.
<svg viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" />
</svg>The four viewBox values represent the minimum x coordinate, minimum y coordinate, width, and height. In this example, the internal coordinate system covers x values from 0 to 100 and y values from 0 to 100.
SVG Width and Height
The width and height attributes define the SVG viewport's displayed dimensions. They are different from the viewBox, which defines the internal coordinate system.
<svg
width="400"
height="200"
viewBox="0 0 200 100"
>
<rect x="0" y="0" width="200" height="100" />
</svg>The graphic uses a 200 by 100 internal coordinate system but is displayed at 400 by 200 CSS pixels. The browser scales the contents accordingly.
Basic SVG Shapes
SVG provides several built-in shape elements for common geometric graphics. These are easier to understand and manipulate than constructing every shape from a path.
| Element | Purpose |
|---|---|
| <rect> | Rectangle or square |
| <circle> | Circle |
| <ellipse> | Ellipse |
| <line> | Straight line |
| <polyline> | Connected series of line segments |
| <polygon> | Closed polygon |
Rectangles
The rect element creates rectangles. Its x and y attributes determine the starting position, while width and height determine its dimensions.
<rect
x="10"
y="20"
width="120"
height="60"
fill="steelblue"
/>Rounded corners can be created with rx and ry.
<rect
x="10"
y="10"
width="120"
height="60"
rx="12"
fill="steelblue"
/>Circles
The circle element uses cx and cy for the center coordinates and r for the radius.
<circle
cx="50"
cy="50"
r="30"
fill="orange"
/>Ellipses
The ellipse element is similar to a circle but has separate horizontal and vertical radii.
<ellipse
cx="100"
cy="50"
rx="80"
ry="35"
fill="purple"
/>Lines
The line element creates a straight line between two points.
<line
x1="10"
y1="10"
x2="190"
y2="90"
stroke="black"
stroke-width="4"
/>Unlike filled shapes, lines normally require the stroke property to become visible.
Polylines and Polygons
The polyline element creates connected line segments without automatically closing the final segment. Polygon creates a closed shape.
<polyline
points="10,90 50,20 90,70 140,10"
fill="none"
stroke="black"
stroke-width="3"
/><polygon
points="50,10 90,80 10,80"
fill="gold"
/>SVG Paths
The path element is one of the most powerful parts of SVG. It can describe lines, curves, arcs, and complex shapes using a compact path data string stored in the d attribute.
<path
d="M 10 90 L 50 10 L 90 90 Z"
fill="none"
stroke="black"
stroke-width="4"
/>M moves the current point, L draws a line, and Z closes the path. More advanced commands support horizontal and vertical lines, Bézier curves, and elliptical arcs.
Many professional icons and illustrations consist primarily of path elements. Understanding paths is therefore important when working with SVG files generated by design tools.
Fill and Stroke
SVG shapes can have both a fill and a stroke. The fill controls the interior of a shape, while stroke controls its outline.
<circle
cx="50"
cy="50"
r="35"
fill="lightblue"
stroke="navy"
stroke-width="5"
/>The stroke-width attribute controls the thickness of the outline. Setting fill to none removes the interior fill while preserving the stroke.
SVG Colors
SVG supports many CSS color formats, including named colors, hexadecimal values, rgb(), rgba(), hsl(), and CSS custom properties when the SVG is used in an appropriate context.
<rect
width="100"
height="100"
fill="#4f46e5"
/>For reusable interface icons, currentColor is especially useful because it allows the SVG to inherit the surrounding text color.
<svg viewBox="0 0 24 24" aria-hidden="true">
<path
d="M12 3v18M3 12h18"
stroke="currentColor"
stroke-width="2"
/>
</svg>Styling SVG with CSS
SVG elements can be styled with presentation attributes such as fill and stroke or with CSS properties. CSS becomes especially useful when the same SVG needs different visual states, such as hover and active states.
.icon {
width: 24px;
height: 24px;
color: #4f46e5;
}
.icon path {
fill: currentColor;
}When an SVG is embedded inline in HTML, CSS can target its internal elements directly. An SVG loaded as an external image with an img element does not expose its internal elements to the surrounding document's CSS in the same way.
Inline SVG
Inline SVG means placing the SVG markup directly inside an HTML document. This is one of the most flexible ways to use SVG on the web.
<button class="icon-button" type="button">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path
d="M12 5v14M5 12h14"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
/>
</svg>
Add
</button>Inline SVG can be styled with CSS, animated, manipulated with JavaScript, and integrated with accessibility attributes. The trade-off is that the SVG markup becomes part of the HTML document rather than being treated as a separate image resource.
SVG with the img Element
SVG files can also be loaded like ordinary images.
<img
src="/images/logo.svg"
alt="Company logo"
width="160"
height="40"
/>Using SVG through img is simple and works well for standalone images such as logos and illustrations. The browser treats the SVG as an external image resource rather than exposing its internal elements to the surrounding page's CSS.
SVG as a CSS Background
SVG can also be used as a CSS background image.
.hero {
background-image: url("/images/pattern.svg");
background-size: cover;
}This approach is useful for decorative graphics and backgrounds. Because the image is decorative from the HTML document's perspective, accessibility requirements differ from those of meaningful content images.
SVG Text
SVG supports text through the text element. Text can be positioned, styled, and transformed like other SVG content.
<svg viewBox="0 0 300 100">
<text
x="20"
y="60"
font-size="32"
fill="black"
>
Hello SVG
</text>
</svg>SVG text can be useful for diagrams and generated graphics, but ordinary HTML text is usually preferable for page content because HTML provides more natural text semantics, layout, accessibility, and search behavior.
SVG Groups
The g element groups multiple SVG elements together. Attributes applied to the group can affect its children, and transformations can be applied to the group as a whole.
<g fill="none" stroke="black" stroke-width="2">
<circle cx="30" cy="30" r="20" />
<rect x="70" y="10" width="40" height="40" />
</g>Groups are useful for organizing complex SVG documents and applying shared styling or transformations.
SVG Transformations
SVG supports transformations such as translation, rotation, scaling, and skewing. Transformations allow the same geometry to be repositioned or resized without changing the original coordinates.
<rect
x="0"
y="0"
width="40"
height="20"
transform="translate(30 20) rotate(30)"
/>Transformations are particularly useful in generated graphics, icons, diagrams, and reusable SVG components.
Responsive SVG
A responsive SVG normally combines a stable viewBox with CSS-controlled dimensions. This allows the graphic to scale while preserving its internal coordinate system.
<svg
class="logo"
viewBox="0 0 240 80"
role="img"
aria-labelledby="logo-title"
>
<title id="logo-title">Example logo</title>
<rect width="240" height="80" rx="12" />
</svg>.logo {
display: block;
width: 100%;
max-width: 240px;
height: auto;
}The viewBox provides the internal 240 by 80 coordinate system, while CSS determines how large the SVG appears on the page.
Preserving the SVG Aspect Ratio
SVG normally preserves the aspect ratio of the viewBox when the viewport and viewBox have different proportions. The preserveAspectRatio attribute can control how the content is aligned and scaled.
<svg
viewBox="0 0 100 100"
preserveAspectRatio="xMidYMid meet"
>
<circle cx="50" cy="50" r="40" />
</svg>The meet behavior scales the content so that the complete viewBox remains visible. Other settings can be used when different cropping or stretching behavior is required.
SVG Accessibility
SVG accessibility depends on whether the graphic conveys meaningful information or is purely decorative. A meaningful SVG should have an accessible name or accompanying text, while a decorative SVG can generally be hidden from assistive technologies.
<svg
viewBox="0 0 24 24"
role="img"
aria-labelledby="icon-title"
>
<title id="icon-title">Download</title>
<path d="M12 3v12" />
</svg>For decorative icons, aria-hidden can prevent redundant announcements when the surrounding text already communicates the same meaning.
<svg
viewBox="0 0 24 24"
aria-hidden="true"
focusable="false"
>
<path d="M12 3v18M3 12h18" />
</svg>SVG Accessibility and Decorative Images
If an SVG communicates information that a user needs to understand, it should not be treated as merely decorative. Charts, diagrams, status indicators, and meaningful illustrations may require accessible text or a suitable accessible name.
For an SVG used only for visual decoration, hiding it from assistive technologies can prevent unnecessary or confusing announcements.
SVG and JavaScript
Inline SVG elements are part of the DOM, so JavaScript can select them, change their attributes, attach event listeners, and animate them.
const circle = document.querySelector(".status-circle");
circle?.setAttribute("fill", "green");This makes SVG useful for interactive charts, diagrams, maps, editors, dashboards, and other interfaces where graphics need to react to application state.
SVG in React
SVG works naturally in React because inline SVG becomes part of the component tree. SVG attributes generally use JSX-compatible property names.
export function PlusIcon() {
return (
<svg
viewBox="0 0 24 24"
width="24"
height="24"
aria-hidden="true"
>
<path
d="M12 5v14M5 12h14"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
/>
</svg>
);
}For reusable icons, React components make it easy to control properties such as size, className, color, accessibility attributes, and other SVG attributes from the parent component.
SVG Sprites
An SVG sprite stores multiple reusable graphics in one SVG document, often using symbol elements. Individual graphics can then be referenced with use.
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="search-icon" viewBox="0 0 24 24">
<circle cx="11" cy="11" r="7" />
<path d="m16 16 5 5" />
</symbol>
</svg>Sprites can reduce repeated SVG markup when an application uses many copies of the same icons. They are particularly common in design systems and component libraries.
SVG Definitions and Reuse
The defs element can contain reusable resources that are not rendered directly. These resources can include gradients, patterns, filters, masks, and reusable shapes.
<svg viewBox="0 0 200 100">
<defs>
<linearGradient id="gradient">
<stop offset="0%" stop-color="blue" />
<stop offset="100%" stop-color="purple" />
</linearGradient>
</defs>
<rect
width="200"
height="100"
fill="url(#gradient)"
/>
</svg>SVG Gradients
SVG supports linear and radial gradients. A gradient can be defined once and applied to shapes through a URL reference.
<linearGradient id="brand-gradient" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="#4f46e5" />
<stop offset="100%" stop-color="#9333ea" />
</linearGradient>Gradients are useful for illustrations and decorative graphics, although complex gradients and filters can increase rendering and file complexity.
SVG Filters
SVG filters can create effects such as blur, shadows, color transformations, and other visual processing. They are powerful but should be used carefully because complex filters can be more expensive to render.
<filter id="shadow">
<feDropShadow
dx="0"
dy="4"
stdDeviation="4"
flood-opacity="0.2"
/>
</filter>SVG File Size and Optimization
SVG files are text-based, which makes them particularly suitable for optimization. Design tools can produce SVG files containing unnecessary metadata, editor-specific namespaces, comments, unused definitions, excessive decimal precision, and redundant attributes.
Removing unnecessary data can reduce file size without changing the visible result. Tools such as SVGO can automate many optimization operations.
- Remove unnecessary metadata and editor information.
- Remove comments that are not needed in production.
- Remove unused definitions.
- Reduce excessive coordinate precision where appropriate.
- Collapse redundant attributes.
- Simplify paths when safe.
- Minify whitespace for production delivery.
Formatting vs Minifying SVG
Formatting and minification solve different problems. A formatted SVG is easier for developers to inspect, review, and modify because elements and attributes are laid out clearly.
A minified SVG removes unnecessary whitespace and other formatting overhead to reduce the transferred file size. Development workflows often keep readable SVG source while producing optimized versions during the build process.
Cleaning SVG Files
SVG files copied from design tools can contain information that is useful to the design application but unnecessary for a website. Cleaning an SVG usually means removing redundant markup while preserving the actual graphical structure.
Before cleaning an SVG, check whether it relies on IDs, CSS classes, masks, clip paths, gradients, filters, animations, scripts, or external references. Removing something that appears unused can break another part of the document.
SVG Security Considerations
SVG is more than a static collection of pixels. Depending on how an SVG is created, embedded, and processed, it can contain elements and features that require security consideration.
Untrusted SVG files should not automatically be treated as harmless user-uploaded images. Applications that accept SVG uploads may need to sanitize them before displaying or serving them, particularly when SVG is inserted inline or otherwise rendered in a context where active content could matter.
SVG MIME Type
The standard media type for SVG is image/svg+xml. Servers should send the appropriate Content-Type when serving SVG resources.
Content-Type: image/svg+xmlCorrect MIME types help browsers and other clients interpret resources consistently and are especially important when SVG files are served as standalone resources.
SVG vs Raster Images
| Characteristic | SVG | PNG/JPEG and other raster formats |
|---|---|---|
| Representation | Vector elements | Pixels |
| Scaling | Usually remains sharp | Can become pixelated when enlarged |
| Best for | Icons, logos, diagrams, illustrations | Photos and complex pixel-based imagery |
| CSS styling | Possible for inline SVG | Not for individual image pixels through ordinary CSS |
| DOM interaction | Possible for inline SVG | Not available for pixels of an ordinary raster image |
| File size | Can be very small for simple graphics | Often more appropriate for photographic content |
When Not to Use SVG
SVG is not the right format for every image. Photographs contain enormous amounts of pixel-level detail and generally benefit from modern raster formats with efficient compression.
SVG can also become inefficient when a graphic contains extremely complex paths, thousands of individual elements, large embedded raster images, or expensive filters. In such cases, another format may provide better performance or a simpler delivery model.
Common SVG Mistakes
- Removing the viewBox and then expecting the SVG to scale predictably.
- Confusing width and height with the internal SVG coordinate system.
- Using SVG for photographs or other highly detailed raster content.
- Forgetting accessibility for meaningful icons, charts, and illustrations.
- Using an SVG icon without an accessible label when the icon is the only control label.
- Leaving unnecessary design-tool metadata in production files.
- Minifying or cleaning an SVG without testing its visual result.
- Assuming every SVG can be safely uploaded and rendered without sanitization.
- Using complex filters when a simpler CSS effect would be sufficient.
- Hard-coding colors when currentColor or CSS variables would make an icon easier to reuse.
A Practical SVG Workflow
A practical workflow starts with the original SVG exported from a design tool or created manually. First inspect the document and identify its viewBox, dimensions, elements, IDs, styles, definitions, and external references.
Next, remove unnecessary metadata and simplify the structure where appropriate. For production assets, run the file through an SVG optimizer and verify that the resulting graphic still renders correctly at the required sizes.
Finally, choose the embedding method based on the purpose of the graphic. Inline SVG is useful when CSS, JavaScript, or accessibility control is important. An img element is often simpler for standalone images, while CSS backgrounds work well for decorative graphics.
A Complete Small SVG Example
The following example combines several basic concepts: a viewBox, a rounded rectangle, a circle, a path, currentColor, and accessibility attributes.
<svg
viewBox="0 0 200 120"
role="img"
aria-labelledby="title"
class="illustration"
>
<title id="title">Simple SVG illustration</title>
<rect
x="10"
y="10"
width="180"
height="100"
rx="16"
fill="#eef2ff"
/>
<circle
cx="70"
cy="60"
r="25"
fill="currentColor"
/>
<path
d="M115 75l18-30 18 30"
fill="none"
stroke="currentColor"
stroke-width="6"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>Frequently Asked Questions
What is SVG used for?
SVG is commonly used for icons, logos, illustrations, diagrams, charts, maps, interface graphics, and other vector-based visuals that need to scale cleanly.
Why is SVG better than PNG for icons?
SVG describes the icon using vector geometry, so it can usually scale to different sizes without becoming pixelated. It can also be styled and manipulated when embedded inline.
What is the SVG viewBox?
The viewBox defines the SVG's internal coordinate system using four values: minimum x, minimum y, width, and height. It allows the SVG content to scale independently of the displayed viewport size.
Can SVG be styled with CSS?
Yes. Inline SVG can be styled with CSS, including properties such as fill, stroke, opacity, and color. Using currentColor is a common technique for making icons inherit the surrounding text color.
Should SVG be inline or used with img?
It depends on the use case. Inline SVG is useful when the graphic needs CSS styling, DOM interaction, animation, or detailed accessibility control. Using img is simpler for many standalone images such as logos and illustrations.
Is SVG responsive?
SVG can be responsive. A stable viewBox combined with CSS-controlled width and height allows the graphic to scale with its container while preserving its internal coordinate system.
Are SVG files safe to accept from users?
Untrusted SVG should be treated as potentially active input rather than assumed to be a harmless image. Applications that accept user-uploaded SVG files should consider sanitization and safe serving strategies before rendering them.
Helpful SVG Tools
An SVG Viewer is useful for inspecting how an SVG renders, while an SVG Formatter makes complex markup easier to read and debug. An SVG Optimizer can reduce unnecessary structure and metadata, and an SVG Minifier can reduce formatting overhead for production delivery. An SVG Cleaner is useful when an exported file contains redundant or unnecessary SVG markup that needs to be reviewed and simplified.
Conclusion
SVG is a powerful web-native format for vector graphics. Its core concepts are straightforward: SVG uses a coordinate system, elements such as rect, circle, line, polygon, and path describe graphics, and attributes such as fill, stroke, width, height, and viewBox control how those graphics are rendered.
For everyday frontend development, the most important concepts to understand are the viewBox, responsive sizing, basic shapes, paths, fill and stroke, CSS integration, accessibility, and the differences between inline SVG and external SVG images.
Once these fundamentals are understood, SVG becomes much easier to work with in React and other frontend frameworks. You can build reusable icons, responsive illustrations, interactive diagrams, and optimized production assets while keeping the graphics sharp at any display size.