SVG Syntax Fundamentals
SVG (Scalable Vector Graphics) is an XML-based vector image format that uses markup syntax to define two-dimensional graphics. Understanding SVG syntax is essential for creating, editing, and optimizing vector graphics for web applications, mobile interfaces, and print media.
Core SVG Concepts
- XML-Based Structure: SVG follows XML syntax rules with opening/closing tags
- Coordinate System: Uses mathematical coordinate system with precise positioning
- Scalability: Vector-based graphics scale infinitely without quality loss
- DOM Integration: SVG elements can be styled with CSS and manipulated with JavaScript
- Accessibility: Built-in support for screen readers and assistive technologies
- Interactivity: Native support for animations, transitions, and user interactions
Basic SVG Document Structure
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
width="200"
height="200"
viewBox="0 0 200 200">
<!-- SVG content goes here -->
<circle cx="100" cy="100" r="50" fill="blue" />
</svg>
This basic structure includes the XML declaration, SVG namespace, dimensions, viewBox, and a simple circle element.
Every SVG element has specific attributes that control its appearance, position, and behavior. Understanding these attributes and how they interact is crucial for creating effective SVG graphics. The syntax follows strict XML rules, making it both powerful and predictable.
Essential SVG Elements Explained
SVG provides a comprehensive set of elements for creating everything from simple shapes to complex illustrations. Each element serves a specific purpose and has unique attributes and capabilities.
🔹 Basic Shape Elements
<rect> - Rectangle
Creates rectangular shapes with optional rounded corners.
<rect x="10" y="10" width="100" height="60" rx="5" ry="5" fill="lightblue" stroke="navy" stroke-width="2" />
- x, y: Top-left corner position
- width, height: Rectangle dimensions
- rx, ry: Corner radius for rounded rectangles
Enhance your rectangles with dynamic effects using our animation tool.
<circle> - Circle
Creates perfect circles with center point and radius.
<circle cx="50" cy="50" r="30" fill="lightgreen" stroke="darkgreen" stroke-width="3" />
- cx, cy: Center point coordinates
- r: Radius of the circle
<ellipse> - Ellipse
Creates elliptical shapes with separate horizontal and vertical radii.
<ellipse cx="100" cy="50" rx="60" ry="30" fill="lavender" stroke="purple" />
- cx, cy: Center point coordinates
- rx: Horizontal radius
- ry: Vertical radius
<line> - Straight Line
Creates straight lines between two points.
<line x1="0" y1="0" x2="100" y2="100" stroke="red" stroke-width="2" />
- x1, y1: Starting point coordinates
- x2, y2: Ending point coordinates
- Note: Lines require stroke to be visible
<polyline> - Connected Lines
Creates series of connected straight lines.
<polyline points="10,10 50,30 90,10 130,30" fill="none" stroke="orange" stroke-width="2" />
- points: Space or comma-separated coordinate pairs
- fill: Usually set to "none" for open shapes
<polygon> - Closed Shape
Creates closed shapes by connecting multiple points.
<polygon points="50,10 90,90 10,90" fill="lightcoral" stroke="darkred" />
- points: Coordinate pairs that define the shape vertices
- Auto-closing: Automatically connects last point to first
📝 Text Elements
<text> - Text Content
Displays text content with full typography control.
<text x="10" y="30"
font-family="Arial, sans-serif"
font-size="20"
fill="darkblue">
Hello SVG World!
</text>
- x, y: Text baseline starting position
- font-family: Font name or family
- font-size: Text size in pixels or other units
- text-anchor: Horizontal alignment (start, middle, end)
<tspan> - Text Span
Provides fine-grained control over text formatting within text elements.
<text x="10" y="30">
Normal text
<tspan font-weight="bold" fill="red">bold red text</tspan>
more normal text
</text>
- dx, dy: Relative positioning offset
- Inheritance: Inherits properties from parent text element
<textPath> - Text Along Path
Renders text along a defined path curve.
<defs>
<path id="curve" d="M 10,90 Q 90,90 90,45" />
</defs>
<text>
<textPath href="#curve">Text follows this curve</textPath>
</text>
- href: References path element by ID
- startOffset: Position along path to start text
🗂️ Structural Elements
<g> - Group
Groups elements together for styling, transforming, or organizing.
<g id="star-group" transform="translate(50,50)" fill="gold">
<polygon points="0,-20 6,-6 20,-6 8,2 12,16 0,8 -12,16 -8,2 -20,-6 -6,-6" />
<circle cx="0" cy="0" r="3" fill="orange" />
</g>
- transform: Apply transformations to all child elements
- Inheritance: Child elements inherit group properties
- Organization: Semantic grouping for maintainable code
<defs> - Definitions
Container for reusable elements like gradients, patterns, and symbols.
<defs>
<linearGradient id="blueGradient">
<stop offset="0%" stop-color="lightblue" />
<stop offset="100%" stop-color="darkblue" />
</linearGradient>
</defs>
<rect width="100" height="50" fill="url(#blueGradient)" />
- Not rendered: Content in defs is not displayed directly
- Reusable: Elements can be referenced multiple times
<use> - Element Reuse
References and reuses defined elements.
<defs>
<circle id="dot" cx="0" cy="0" r="5" fill="red" />
</defs>
<use href="#dot" x="10" y="10" />
<use href="#dot" x="30" y="30" />
<use href="#dot" x="50" y="50" />
- href: References element by ID
- x, y: Position offset for the referenced element
🎯 Practice with Interactive Examples
The best way to learn SVG syntax is through hands-on practice. Use our interactive SVG code editor to:
- Experiment with all SVG elements in real-time
- See immediate visual results as you type
- Learn proper syntax through trial and error
- Build complex graphics step by step
- Copy and modify working examples
Coordinate Systems and ViewBox
Understanding SVG coordinate systems is crucial for precise positioning and scaling. SVG uses a mathematical coordinate system where the origin (0,0) is at the top-left corner, with x increasing to the right and y increasing downward.
SVG Coordinate System Basics
Coordinate Fundamentals
- Origin (0,0): Top-left corner of the SVG canvas
- X-axis: Increases from left to right
- Y-axis: Increases from top to bottom
- Units: Default is pixels, but supports various units
- Precision: Supports decimal coordinates for precise positioning
Viewport vs ViewBox
- Viewport: The visible area (width/height attributes)
- ViewBox: The coordinate system used internally
- Scaling: ViewBox enables automatic scaling
- Aspect Ratio: preserveAspectRatio controls scaling behavior
ViewBox in Detail
The viewBox attribute is one of the most powerful features in SVG, enabling responsive and scalable graphics.
<svg width="200" height="100" viewBox="0 0 400 200">
ViewBox Syntax
viewBox="min-x min-y width height"
- min-x, min-y: Top-left corner of viewBox
- width, height: ViewBox dimensions
Example Result
This creates a 200×100 pixel viewport that displays a 400×200 coordinate system, effectively scaling content to 50% size.
Common ViewBox Patterns
viewBox="0 0 100 100"
- Standard 100×100 unit squareviewBox="-50 -50 100 100"
- Centered coordinate systemviewBox="0 0 1920 1080"
- HD aspect ratio coordinatesPreserveAspectRatio Control
The preserveAspectRatio attribute controls how SVG scales when the viewport and viewBox have different aspect ratios.
Syntax
preserveAspectRatio="[alignment] [meetOrSlice]"
Alignment Options
xMinYMin
- Top-left alignmentxMidYMid
- Center alignment (default)xMaxYMax
- Bottom-right alignmentnone
- Disable uniform scaling
Meet or Slice
meet
- Scale to fit entirely (default)slice
- Scale to fill, may crop content
Practical Examples
preserveAspectRatio="xMidYMid meet"
- Center and scale to fitpreserveAspectRatio="none"
- Stretch to fill viewportpreserveAspectRatio="xMinYMin slice"
- Align top-left, crop if neededSVG Transforms
SVG transforms allow you to modify the coordinate system of elements, enabling translation, rotation, scaling, and skewing. Understanding transforms is essential for creating dynamic and responsive SVG graphics.
Transform Functions
translate(x, y)
Moves elements by specified distances.
<rect x="0" y="0" width="50" height="30" transform="translate(100, 50)" />
Moves the rectangle 100 units right and 50 units down.
rotate(angle, cx, cy)
Rotates elements around a center point.
<rect x="0" y="0" width="50" height="30" transform="rotate(45, 25, 15)" />
Rotates 45 degrees around the rectangle's center point.
scale(sx, sy)
Scales elements uniformly or non-uniformly.
<circle cx="25" cy="25" r="20" transform="scale(1.5, 0.8)" />
Scales 1.5× horizontally and 0.8× vertically.
skewX(angle) / skewY(angle)
Skews elements along the X or Y axis.
<rect x="10" y="10" width="40" height="40" transform="skewX(15)" />
Creates a 15-degree horizontal skew effect.
matrix(a, b, c, d, e, f)
Applies custom transformation matrix for complex transforms.
<rect x="0" y="0" width="30" height="30" transform="matrix(1, 0.5, -0.5, 1, 30, 10)" />
Applies combined scaling, skewing, and translation.
Combining Transforms
Multiple transforms can be combined by listing them in sequence. The order matters as transforms are applied from right to left.
<!-- Applied in order: translate, then rotate, then scale -->
<rect transform="scale(1.2) rotate(30) translate(50, 20)"
width="40" height="20"
fill="lightblue" />
⚠️ Transform Order Matters
translate(50, 0) rotate(45)
produces different results than rotate(45) translate(50, 0)
. Always consider the coordinate system after each transform.
The Powerful <path> Element
The path element is the most versatile and powerful drawing element in SVG. It can create any shape that can be drawn with the other elements, and much more. Understanding path syntax opens up unlimited creative possibilities.
Path Data (d attribute) Syntax
Path data consists of commands followed by parameters. Commands use single letters, with uppercase for absolute coordinates and lowercase for relative coordinates.
Command | Name | Parameters | Description |
---|---|---|---|
M, m | MoveTo | x y | Move to a point without drawing |
L, l | LineTo | x y | Draw line to specified point |
H, h | Horizontal Line | x | Horizontal line to x coordinate |
V, v | Vertical Line | y | Vertical line to y coordinate |
C, c | Cubic Bézier | x1 y1 x2 y2 x y | Cubic curve with two control points |
S, s | Smooth Cubic | x2 y2 x y | Smooth cubic curve |
Q, q | Quadratic Bézier | x1 y1 x y | Quadratic curve with one control point |
T, t | Smooth Quadratic | x y | Smooth quadratic curve |
A, a | Arc | rx ry x-axis-rotation large-arc-flag sweep-flag x y | Elliptical arc |
Z, z | ClosePath | none | Close current path |
Path Examples
Simple Triangle
<path d="M 10,30 L 50,5 L 90,30 Z" fill="lightblue" stroke="navy" />
Move to (10,30), draw line to (50,5), line to (90,30), then close path.
Curved Heart Shape
<path d="M 20,30 C 20,20 40,20 40,30 C 40,20 60,20 60,30 C 60,40 40,60 40,60 C 40,60 20,40 20,30 Z" fill="red" />
Uses cubic Bézier curves to create smooth heart shape with proper closure.
Arc-based Circle
<path d="M 50,25 A 25,25 0 1,1 49.99,25" fill="none" stroke="purple" stroke-width="2" />
Creates a complete circle using arc command with large-arc-flag set.
🔧 Master Path Syntax
Path syntax can be complex, but practice makes perfect. Use our SVG editor to:
- Experiment with different path commands
- See real-time visual feedback as you edit
- Learn curve control points through interaction
- Build complex shapes step by step
- Copy working examples for your projects
SVG Styling and Presentation
SVG elements can be styled using presentation attributes, CSS styles, or external stylesheets. Understanding the different styling methods and their precedence is crucial for maintainable SVG code. Generate professional graphics instantly with our AI SVG generator to see these styling concepts in action.
Styling Methods
1. Presentation Attributes
Direct attribute styling on SVG elements.
<circle cx="50" cy="50" r="20" fill="red" stroke="blue" stroke-width="2" />
- Lowest specificity in CSS cascade
- Good for simple, one-off styling
- Easy to read and understand
2. Inline CSS Styles
CSS properties in the style attribute.
<circle cx="50" cy="50" r="20" style="fill: red; stroke: blue; stroke-width: 2px;" />
- Higher specificity than presentation attributes
- Can use CSS-specific features like calc()
- Supports CSS animations and transitions
3. Internal Stylesheets
CSS within <style> element in SVG.
<svg>
<style>
.my-circle {
fill: red;
stroke: blue;
stroke-width: 2px;
}
.my-circle:hover {
fill: orange;
}
</style>
<circle cx="50" cy="50" r="20" class="my-circle" />
</svg>
- Supports pseudo-classes and pseudo-elements
- Enables responsive design with media queries
- Allows complex selectors and cascade
4. External Stylesheets
Link to external CSS files.
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="styles.css" ?>
<svg xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="20" class="styled-circle" />
</svg>
- Best for reusable styles across multiple SVGs
- Supports all CSS features and frameworks
- Cacheable and maintainable
Essential SVG CSS Properties
Fill Properties
fill
- Interior color or patternfill-opacity
- Fill transparency (0-1)fill-rule
- How overlapping areas are filled
Stroke Properties
stroke
- Outline colorstroke-width
- Outline thicknessstroke-opacity
- Stroke transparencystroke-linecap
- Line ending stylestroke-linejoin
- Corner stylestroke-dasharray
- Dashed line pattern
Example: Advanced Stroke Styling
<path d="M 10,10 L 100,10 L 100,100"
fill="none"
stroke="red"
stroke-width="3"
stroke-linecap="round"
stroke-linejoin="round"
stroke-dasharray="10,5" />
Best Practices for SVG Syntax
Following best practices ensures your SVG code is maintainable, accessible, performant, and compatible across different browsers and applications.
✅ Syntax Best Practices
- Always declare namespace: Include xmlns="http://www.w3.org/2000/svg"
- Use viewBox: Enable responsive scaling with proper viewBox
- Meaningful IDs: Use descriptive, unique IDs for referenceable elements
- Group logically: Use <g> elements to organize related content
- Optimize paths: Simplify path data while maintaining visual quality
- Consistent formatting: Use proper indentation and line breaks
- Remove unused elements: Clean up unnecessary groups and definitions
📱 Accessibility Best Practices
- Add titles and descriptions: Use <title> and <desc> elements
- ARIA labels: Include aria-label for interactive elements
- Semantic roles: Use role="img" for decorative graphics
- Color independence: Don't rely solely on color to convey information
- Focus indicators: Ensure interactive elements are keyboard accessible
- Alt text alternatives: Provide text alternatives for complex graphics
⚡ Performance Best Practices
- Minimize file size: Remove unnecessary whitespace and comments
- Optimize decimal places: Limit coordinate precision to needed accuracy
- Reuse elements: Use <use> and <defs> for repeated graphics
- Avoid deep nesting: Flatten unnecessary group hierarchies
- Efficient transforms: Combine multiple transforms when possible
- Smart gradients: Reuse gradient definitions across elements
🔧 Maintenance Best Practices
- Version control friendly: Format code consistently for diff clarity
- Comment complex sections: Explain non-obvious path calculations
- Modular design: Break complex graphics into reusable components
- Validate regularly: Check syntax and accessibility during development
- Test across browsers: Ensure consistent rendering in target browsers
- Document coordinate systems: Note custom viewBox and coordinate assumptions
Conclusion: Master SVG Syntax
Understanding SVG syntax is fundamental to creating professional, scalable vector graphics. From basic shapes to complex paths, coordinate systems to transforms, each concept builds upon the others to give you complete control over your vector graphics.
🚀 Start Creating with SVG Today
Ready to put your SVG syntax knowledge into practice? Use our professional SVG code editor to:
- Write SVG code with syntax highlighting
- See real-time visual results
- Learn through interactive examples
- Experiment with all SVG elements
- Test coordinate systems and transforms
- Master complex path syntax
- Validate your code automatically
- Export working SVG files