SVG tutorial and reference

What Is SVG? Elements, Attributes, and Path d Guide

SVG means Scalable Vector Graphics: an XML-based image format for drawing responsive icons, logos, illustrations, charts, diagrams, maps, and UI graphics with coordinates instead of pixels. This SVG tutorial and reference explains the svg tag, g tag, path tag, path d attribute, viewBox, transforms, fill, stroke, text, gradients, masks, filters, animation, and the most common SVG attributes used in real SVG code.

SVG Quick Answers

These short answers cover the most common SVG questions before the full element and attribute reference below.

What is SVG?

SVG stands for Scalable Vector Graphics. It is an XML-based vector image format for icons, logos, illustrations, charts, maps, UI graphics, and animated web artwork.

What is the svg tag?

The svg tag is the root element. It creates the viewport, declares the SVG namespace, and usually defines width, height, and viewBox.

What is the g tag in SVG?

The g tag groups child elements. A group can share transform, opacity, filter, clip-path, mask, class, and event behavior.

What is the SVG path tag?

The path tag draws custom shapes with the d attribute. It can describe straight lines, curves, arcs, icons, blobs, logos, and complex illustrations.

What is the d attribute in SVG?

The d attribute is path data: a command string such as M, L, C, Q, A, and Z that tells the browser how to draw a path.

What are SVG attributes?

SVG attributes are name/value settings on elements. They control geometry, paint, transforms, text, references, filters, masks, animation, accessibility, and metadata.

How SVG Code Works

SVG viewport

The rendered rectangle on screen. On the root svg element, width and height usually set it.

SVG viewBox

The internal coordinate system. A viewBox of 0 0 1024 1024 gives you a 1024-unit vector canvas.

SVG elements

Tags such as rect, path, g, text, and image. SVG attributes define their geometry and style.

SVG Code Example

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
  <g transform="translate(10 10)">
    <rect x="0" y="0" width="80" height="80" rx="12" fill="#6c5ce7" />
    <path d="M 25 55 L 50 20 L 75 55 Z" fill="#ffcb3b" stroke="#0a0a0b" />
  </g>
</svg>

The svg tag creates the coordinate space. The g tag moves everything inside it. The rect element draws a rounded square. The path element draws a triangle with the d attribute string.

SVG Tags and Elements Reference

<svg>

Root viewport and coordinate system for an SVG document or nested SVG fragment.

Key attributes
xmlnsviewBoxwidthheightxypreserveAspectRatio
Editor note
Use viewBox to make artwork scalable. Width and height describe the rendered viewport size.

<g>

Group related elements so they can share transforms, styles, masks, filters, and events.

Key attributes
idclasstransformopacityclip-pathmaskfilter
Editor note
Editors usually select and move a group as one object, while its children keep their own geometry.

<defs>

Store reusable definitions that do not render directly.

Key attributes
id
Editor note
Common children are gradients, symbols, markers, filters, masks, patterns, and clip paths.

<symbol>

Define a reusable graphic with its own viewBox.

Key attributes
idviewBoxrefXrefYpreserveAspectRatio
Editor note
Place a symbol with use. Good for icons and repeated components.

<use>

Clone and render a referenced element.

Key attributes
hrefxlink:hrefxywidthheight
Editor note
Modern SVG uses href. xlink:href is legacy but still appears in old files.

<path>

Draw arbitrary outlines using path data.

Key attributes
dpathLengthfillstrokestroke-width
Editor note
The d attribute is the main geometry string. Most complex SVG artwork is built from paths.

<rect>

Draw rectangles and rounded rectangles.

Key attributes
xywidthheightrxry
Editor note
rx and ry round the horizontal and vertical corners.

<circle>

Draw a circle from a center point and radius.

Key attributes
cxcyr
Editor note
cx and cy are the center. r is the radius.

<ellipse>

Draw an oval from a center point and two radii.

Key attributes
cxcyrxry
Editor note
rx is the horizontal radius. ry is the vertical radius.

<line>

Draw a straight segment between two points.

Key attributes
x1y1x2y2strokestroke-width
Editor note
Lines need stroke to be visible; fill does not apply.

<polyline>

Draw connected open line segments.

Key attributes
pointsfillstroke
Editor note
points is a list like 0,0 50,20 80,80. Usually fill is none.

<polygon>

Draw connected closed line segments.

Key attributes
pointsfillstroke
Editor note
Like polyline, but the final point connects back to the first point.

<text>

Render editable text in SVG coordinates.

Key attributes
xydxdyrotatetextLengthlengthAdjust
Editor note
Text can use CSS font properties and can inherit paint attributes.

<tspan>

Style or position part of a text element.

Key attributes
xydxdyrotatetextLengthlengthAdjust
Editor note
Use tspans for multi-line text or mixed styles inside one text element.

<textPath>

Place text along a path.

Key attributes
hrefstartOffsetmethodspacingsidepath
Editor note
Commonly references a path in defs with href.

<image>

Embed raster images or external SVG images.

Key attributes
hrefxywidthheightpreserveAspectRatiocrossorigindecoding
Editor note
External images can have CORS and security implications.

<a>

Make child SVG content a hyperlink.

Key attributes
hreftargetdownloadrel
Editor note
Works like an HTML link around SVG graphics.

<clipPath>

Define a clipping shape that hides content outside the clip region.

Key attributes
idclipPathUnitstransform
Editor note
Apply with clip-path="url(#id)".

<mask>

Define alpha/luminance masking.

Key attributes
idxywidthheightmaskUnitsmaskContentUnits
Editor note
White reveals, black hides, gray partially reveals.

<pattern>

Define repeated paint content.

Key attributes
idxywidthheightpatternUnitspatternContentUnitspatternTransform
Editor note
Apply with fill="url(#patternId)" or stroke="url(#patternId)".

<marker>

Define arrowheads or symbols attached to line/path vertices.

Key attributes
idviewBoxrefXrefYmarkerWidthmarkerHeightmarkerUnitsorient
Editor note
Apply with marker-start, marker-mid, or marker-end.

<linearGradient>

Define a gradient along a line.

Key attributes
idx1y1x2y2gradientUnitsgradientTransformspreadMethodhref
Editor note
Contains stop children. Apply with fill="url(#id)".

<radialGradient>

Define a circular or focal gradient.

Key attributes
idcxcyrfxfyfrgradientUnitsgradientTransformspreadMethodhref
Editor note
fx, fy, and fr control the focal circle.

<stop>

Define one color stop inside a gradient.

Key attributes
offsetstop-colorstop-opacity
Editor note
offset can be a number or percentage.

<filter>

Define a chain of filter primitives.

Key attributes
idxywidthheightfilterUnitsprimitiveUnits
Editor note
Apply with filter="url(#id)". Children include feGaussianBlur, feColorMatrix, and more.

<title / desc / metadata>

Add accessibility, description, and machine-readable metadata.

Key attributes
idlang
Editor note
title and desc can improve accessible names and document understanding.

SVG Path d Attribute Commands

The path d attribute is a compact drawing language inside the SVG path tag. It is a list of commands and numbers. Uppercase SVG path commands use absolute coordinates. Lowercase commands use coordinates relative to the current point.

CommandNameWhat it does
M / mMove toStarts a new subpath at x y. Lowercase is relative.
L / lLine toDraws a straight line to x y.
H / hHorizontal lineDraws a horizontal line to x.
V / vVertical lineDraws a vertical line to y.
C / cCubic BezierUses two control points and an end point.
S / sSmooth cubic BezierReflects the previous cubic control point.
Q / qQuadratic BezierUses one control point and an end point.
T / tSmooth quadratic BezierReflects the previous quadratic control point.
A / aElliptical arcDraws an arc using radii, rotation, flags, and endpoint.
Z / zClose pathConnects back to the current subpath start.

Example: d="M 10 10 L 90 10 L 50 80 Z" moves to 10,10, draws two lines, then closes the shape.

SVG Attribute Reference: viewBox, Transform, Fill, Stroke, Text, Filters

SVG attributes fall into families. Some are global. Some only work on specific elements. Presentation attributes often mirror CSS properties, while geometry attributes define the shape itself. This reference covers common SVG attributes for scalable vector graphics, including viewBox, transform, fill, stroke, width, height, points, href, clip-path, mask, filter, gradients, text, and animation.

Global and document attributes

Accepted broadly across SVG elements, especially graphics and container elements.

AttributePurpose
idUnique identifier for references, CSS, scripts, and editor selection.
classCSS class list.
styleInline CSS declarations.
lang, xml:langLanguage metadata.
tabindexKeyboard focus order.
role, aria-*Accessibility roles and states.
data-*Custom application metadata.
requiredExtensions, systemLanguageConditional processing.
on*Event handler attributes such as onclick. Avoid in uploaded SVG for security.

Viewport and coordinate attributes

Define the canvas, coordinate system, and scaling behavior.

AttributePurpose
xmlnsSVG namespace on standalone root svg elements.
viewBoxMaps internal coordinates: min-x min-y width height.
width, heightRendered size or nested viewport size.
x, yPosition for nested svg, image, use, rect, text, and similar elements.
preserveAspectRatioControls how viewBox scales into the viewport.
transformApplies translate, rotate, scale, skew, or matrix transforms.
transform-originOrigin point for CSS/SVG transforms where supported.
vector-effectCommonly non-scaling-stroke so stroke width ignores transforms.

Geometry attributes

Define the actual shape for basic elements.

AttributePurpose
dPath data string on path: move, line, curve, arc, and close commands.
pathLengthAuthor-specified total path length for dash and text calculations.
x, y, width, heightRectangle, image, use, pattern, mask, filter, and viewport geometry.
rx, ryRectangle corner radii or ellipse radii depending on element.
cx, cy, rCircle/radial-gradient center and radius.
x1, y1, x2, y2Line endpoints or gradient line endpoints.
pointsPoint list for polyline and polygon.

Paint and presentation attributes

Style the visible result. Many presentation attributes can also be CSS properties.

AttributePurpose
fillInterior paint: color, none, currentColor, or url(#paint).
fill-opacityOpacity of fill paint.
fill-ruleHow holes are calculated: nonzero or evenodd.
strokeOutline paint.
stroke-widthOutline thickness.
stroke-linecapEndpoint shape: butt, round, square.
stroke-linejoinCorner join: miter, round, bevel.
stroke-miterlimitLimit for sharp miter joins.
stroke-dasharrayDash/gap pattern.
stroke-dashoffsetDash pattern offset.
stroke-opacityOpacity of stroke paint.
opacityWhole element opacity after painting.
display, visibilityWhether the element participates in rendering.
pointer-eventsSVG hit testing behavior for mouse/touch selection.
cursorPointer cursor over the element.
clip-path, clip-ruleClipping reference and clipping fill rule.
maskMask reference.
filterFilter reference.
marker-start, marker-mid, marker-endAttach markers to path/line vertices.
colorCurrent color used by currentColor.
paint-orderOrder of fill, stroke, and markers.
shape-rendering, text-rendering, image-renderingRendering quality hints.

Text attributes

Position and shape SVG text.

AttributePurpose
x, y, dx, dyAbsolute or relative glyph positioning.
rotatePer-glyph or whole text rotation.
textLengthForce text into a target length.
lengthAdjustChoose spacing-only or spacing-and-glyphs adjustment.
text-anchorStart, middle, or end alignment around x.
dominant-baseline, alignment-baseline, baseline-shiftVertical baseline alignment.
font-family, font-size, font-weight, font-styleFont selection and styling.
letter-spacing, word-spacingSpacing adjustments.
direction, unicode-bidi, writing-modeBidirectional and vertical text behavior.
startOffset, method, spacing, sideText-on-path positioning on textPath.

References, gradients, patterns, clips, masks, and markers

Connect one SVG element to reusable definitions.

AttributePurpose
hrefModern reference attribute for use, image, a, gradients, textPath, and animation.
xlink:hrefLegacy reference attribute in older SVG files.
gradientUnits, gradientTransform, spreadMethodGradient coordinate system, transform, and repeat behavior.
offset, stop-color, stop-opacityGradient stop location and paint.
patternUnits, patternContentUnits, patternTransformPattern sizing, internal coordinate system, and transform.
clipPathUnitsCoordinate system for clipPath children.
maskUnits, maskContentUnitsCoordinate systems for mask region and contents.
markerUnits, markerWidth, markerHeight, refX, refY, orientMarker sizing, anchor point, and rotation behavior.

Filter attributes

Filter elements define a processing pipeline.

AttributePurpose
filterUnits, primitiveUnitsCoordinate systems for filter region and primitive inputs.
in, in2, resultNamed filter inputs and outputs.
x, y, width, heightFilter or primitive region.
stdDeviationBlur amount for feGaussianBlur.
modeBlend mode for feBlend.
operator, k1, k2, k3, k4Composite/arithmetic operation parameters.
type, valuesColor matrix type and numeric matrix/list.
tableValues, slope, intercept, amplitude, exponent, offsetComponent transfer function values.
baseFrequency, numOctaves, seed, stitchTilesNoise generation settings.
scale, xChannelSelector, yChannelSelectorDisplacement map settings.
surfaceScale, diffuseConstant, specularConstant, specularExponentLighting settings.
azimuth, elevation, pointsAtX, pointsAtY, pointsAtZ, limitingConeAngleLight source direction and target.
kernelMatrix, order, divisor, bias, targetX, targetY, edgeMode, kernelUnitLength, preserveAlphaConvolution settings.

Animation attributes

SMIL animation is still present in many SVG references and files.

AttributePurpose
attributeName, attributeTypeWhich attribute/property to animate.
begin, dur, end, min, maxAnimation timing.
repeatCount, repeatDur, restartRepeat behavior.
from, to, by, valuesAnimated values.
calcMode, keyTimes, keySplinesInterpolation and easing.
additive, accumulateHow animation values combine.
path, keyPoints, rotate, originMotion path animation settings.

SVG is large. For exact element-by-element support and rare attributes, use the official SVG 2 specification and the MDN reference.