SVG Embedded in HTML
There are various ways to use SVG in web pages. This chapter will introduce different embedding methods and their pros and cons.
Method 1: Inline SVG
The most direct way is to write SVG code directly in HTML:
Pros
- Can style with CSS
- Can manipulate elements with JavaScript
- No additional HTTP requests
- Supports all SVG features
Cons
- HTML file size increases
- Cannot be cached by browser
- Code can become cluttered
Method 2: Using <img> Tag
Import SVG as an image file:
Pros
- Simple syntax, same as regular images
- Can be cached by browser
- Keeps HTML clean
Cons
- Cannot modify SVG internal styles with CSS
- Cannot manipulate SVG elements with JavaScript
- Does not support scripts in SVG animations
Method 3: Using CSS Background Image
Use SVG as CSS background:
Pros
- Easy to control size and position with CSS
- Can be cached by browser
- Suitable for decorative graphics
Cons
- Cannot manipulate SVG internal elements
- Not suitable for interactive graphics
Method 4: Using <object> Tag
Pros
- Can be cached by browser
- Supports fallback content
- Scripts inside SVG can run
Cons
- Cross-domain access restricted
- Style isolation, external CSS cannot affect internal styles
Method 5: Using <iframe> Tag
Pros
- Completely isolated environment
- Scripts inside SVG can run
Cons
- Styles completely isolated
- Cross-domain operations restricted
- Increases page complexity
Method 6: Using Data URI
Encode SVG as Base64 or embed directly:
Pros
- Reduces HTTP requests
- Suitable for small icons
Cons
- Not readable, difficult to maintain
- Base64 increases file size by about 33%
- Cannot be cached separately
Best Practice Selection
SVG Symbol Usage
For icon systems, Symbol is recommended:
viewBox Attribute
viewBox is one of the most important SVG attributes, defining the SVG coordinate system:
viewBox="0 0 100 50" means:
0 0: Starting point coordinates (x, y)100 50: Viewport width and height
This allows SVG to scale responsively.
Responsive SVG
Create responsive SVG:
Key points:
- Set
viewBoxinstead of fixedwidth/height - Use CSS to control actual dimensions
Next Steps
Now you understand how to use SVG in HTML, let's learn how to draw SVG Rectangle!