HTML - SVG
Introduction to SVG
SVG (Scalable Vector Graphics) is an XML-based format for creating vector graphics on the web. Unlike raster images (JPEGs or PNGs) made up of pixels, SVG graphics are defined using mathematical instructions, allowing them to be scaled to any size without losing quality.
One of the main advantages of using SVG is its ability to create clear graphics that look good on any screen size. Whether you're viewing an SVG image on a small mobile device or a large desktop monitor, the graphics will remain sharp. This makes SVG good for creating logos, icons, charts, and other graphics that need to be resized often.
Another benefit of SVG is its small file size compared to raster images. Because SVG graphics are defined using code rather than pixels, they can be compressed and optimized to reduce their file size without sacrificing image quality. This means faster page load times and better performance, especially on mobile devices or slower internet connections.
When comparing SVG to raster images, consider the type of graphic you're creating. Raster images are best for photographs with many colors and details. SVG excels at creating simple, geometric shapes, icons, and illustrations with solid colors or gradients. SVG graphics can also be animated and made interactive using JavaScript, opening up possibilities for engaging web content.
Example HTML code with extra spaces
<p>This is a paragraph with extra spaces.</p>
When a browser renders this code, it will display the text as:
This is a paragraph with extra spaces.
Example of mismatched tags
<p>This is a paragraph.</div>
In this case, the opening <p>
tag is closed with a </div>
tag, which is incorrect. The right way to close the paragraph is:
<p>This is a paragraph.</p>
Basic SVG Syntax
To start using SVG, you need to understand its basic syntax and document structure. SVG code is written in XML format, which means it follows a set of rules for defining elements and attributes.
The first thing to include in an SVG document is the XML declaration and the SVG namespace. The namespace tells the browser that the code is written in SVG format.
Example: Starting an SVG document
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg">
<!-- SVG content goes here -->
</svg>
The <svg>
element is the root element of an SVG document. All other SVG elements are placed inside it. The xmlns
attribute specifies the SVG namespace, which is always "http://www.w3.org/2000/svg"
.
Two attributes of the <svg>
element are width
and height
. These define the size of the SVG viewport, which is the visible area of the SVG image. You can specify the width and height in pixels or other units:
Example: Setting width and height for SVG
<svg xmlns="http://www.w3.org/2000/svg" width="500" height="300">
<!-- SVG content goes here -->
</svg>
Another attribute to know is viewBox
. It defines the coordinate system and aspect ratio of the SVG image. The viewBox
attribute takes four values: x
, y
, width
, and height
. The x
and y
values specify the top-left corner of the viewBox, while width
and height
define its size:
Example: Defining the viewBox for SVG
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<!-- SVG content goes here -->
</svg>
The viewBox starts at coordinates (0, 0) and has a width and height of 100 units each. The SVG image will be scaled to fit within the viewport while keeping its aspect ratio.
SVG uses a coordinate system where the top-left corner is (0, 0), and values increase to the right and down. You can specify coordinates and lengths in various units, such as pixels (px), em, rem, or percentages. However, the most common units in SVG are user units, which are defined by the viewBox
attribute.
Drawing Basic Shapes
SVG provides several basic shapes that you can use to create graphics. These shapes include rectangles, circles, ellipses, lines, polygons, polylines, and paths.
To draw a rectangle, use the <rect>
element. You can specify the position and size of the rectangle using the x
, y
, width
, and height
attributes. The x
and y
attributes define the coordinates of the top-left corner, while width
and height
set the dimensions of the rectangle:
Example: Drawing a Rectangle
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<rect x="10" y="10" width="50" height="30" />
</svg>
To create a circle, use the <circle>
element. Specify the position of the center using the cx
and cy
attributes, and set the radius with the r
attribute:
Example: Creating a Circle
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="25" />
</svg>
For an ellipse, use the <ellipse>
element. Similar to a circle, set the center position with cx
and cy
, but instead of a single radius, use the rx
and ry
attributes to define the horizontal and vertical radii:
Example: Creating an Ellipse
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<ellipse cx="50" cy="50" rx="30" ry="20" />
</svg>
To draw a line, use the <line>
element. Specify the starting point with the x1
and y1
attributes and the ending point with x2
and y2
:
Example: Drawing a Line
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<line x1="10" y1="10" x2="90" y2="90" />
</svg>
For creating complex shapes with straight lines, use the <polygon>
or <polyline>
elements. Both take a points
attribute that defines the vertices of the shape. The difference is that a polygon automatically closes the shape, while a polyline leaves it open:
Example: Creating a Polygon and Polyline
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<polygon points="50,10 90,90 10,90" />
<polyline points="10,50 50,10 90,50" />
</svg>
When you need to create complex curves and shapes, use the <path>
element. It takes a d
attribute that defines the path using a series of commands and coordinates. Some common commands include M
(move to), L
(line to), H
(horizontal line), V
(vertical line), C
(cubic Bezier curve), and Z
(close path):
Example: Creating a Complex Path
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<path d="M10,50 C10,10 90,10 90,50 C90,90 10,90 10,50 Z" />
</svg>
These basic shapes give you the building blocks to create a variety of graphics with SVG. You can combine them, style them, and transform them to achieve the desired look for your projects.
Styling SVG Elements
SVG provides ways to style and change the appearance of elements. You can use attributes like fill
and stroke
to set colors, opacity for transparency, gradients and patterns for texture, and even CSS for more advanced styling.
To set the fill color of an SVG element, use the fill
attribute. This attribute accepts color keywords, hex values, RGB, or HSL:
Example: Set the fill color of an SVG element
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<rect x="10" y="10" width="50" height="30" fill="blue" />
<circle cx="50" cy="50" r="25" fill="#ff0000" />
</svg>
The stroke is the outline of an SVG shape. Set the stroke color using the stroke
attribute and control its width with stroke-width
:
Example: Set the stroke color and width of an SVG shape
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<rect x="10" y="10" width="50" height="30" fill="none" stroke="blue" stroke-width="2" />
<circle cx="50" cy="50" r="25" fill="none" stroke="#ff0000" stroke-width="4" />
</svg>
To make an element transparent, use the opacity
attribute. It accepts values between 0 (fully transparent) and 1 (fully opaque):
Example: Set the opacity of an SVG element
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<rect x="10" y="10" width="50" height="30" fill="blue" opacity="0.5" />
<circle cx="50" cy="50" r="25" fill="#ff0000" opacity="0.7" />
</svg>
You can also set the fill or stroke opacity separately using fill-opacity
and stroke-opacity
.
SVG supports linear and radial gradients for creating smooth color transitions. Define the gradient using the <linearGradient>
or <radialGradient>
element and reference it in the fill
or stroke
attribute using a URL:
Example: Use linear gradients in SVG
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<defs>
<linearGradient id="myGradient">
<stop offset="0%" stop-color="blue" />
<stop offset="100%" stop-color="red" />
</linearGradient>
</defs>
<rect x="10" y="10" width="50" height="30" fill="url(#myGradient)" />
</svg>
Patterns allow you to fill shapes with repeating images or other SVG elements. Define the pattern using the <pattern>
element and reference it in the fill
or stroke
attribute:
Example: Use patterns in SVG
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<defs>
<pattern id="myPattern" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
<circle cx="10" cy="10" r="5" fill="blue" />
</pattern>
</defs>
<rect x="10" y="10" width="50" height="30" fill="url(#myPattern)" />
</svg>
In addition to attributes, you can style SVG elements using CSS. Apply CSS rules to SVG elements using inline styles, internal stylesheets, or external stylesheets:
Example: Style SVG elements using CSS
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<style>
.myStyle {
fill: blue;
stroke: red;
stroke-width: 2;
}
</style>
<rect x="10" y="10" width="50" height="30" class="myStyle" />
</svg>
Using CSS allows for more flexible and reusable styling, as you can target elements based on their tag names, classes, or IDs.
By combining these styling techniques, you can create visually appealing and customized SVG graphics that fit your project's design and requirements.
Text in SVG
Adding text to your SVG graphics is easy using the <text>
element. You can position the text using the x
and y
attributes, which specify the coordinates of the text's anchor point. By default, the anchor point is the left edge of the text's baseline:
Basic Text Example
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100">
<text x="20" y="35">Hello, SVG!</text>
</svg>
To format and style the text, you can use various attributes or CSS properties. For example, you can change the font family, size, weight, and style using the font-family
, font-size
, font-weight
, and font-style
attributes:
Styled Text Example
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100">
<text x="20" y="35" font-family="Arial" font-size="24" font-weight="bold" font-style="italic">
Hello, SVG!
</text>
</svg>
You can also apply fill and stroke colors to the text, adjust the text anchor point using the text-anchor
attribute (with values like start
, middle
, or end
), and control the spacing between characters or words using the letter-spacing
and word-spacing
attributes.
If you need to wrap text or create multiline text, you can use the <tspan>
element inside the <text>
element. Each <tspan>
represents a separate line of text and can have its own positioning and styling:
Multiline Text Example
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100">
<text x="20" y="35">
<tspan>Hello,</tspan>
<tspan x="20" y="60">SVG!</tspan>
</text>
</svg>
Another interesting feature of SVG text is the ability to place it along a path. To do this, first define a path using the <path>
element. Then, use the <textPath>
element inside the <text>
element and reference the path using the href
attribute:
Text Along a Path Example
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100">
<path id="myPath" d="M20,20 C20,50 180,50 180,20" fill="none" stroke="black" />
<text>
<textPath href="#myPath">Text along a path</textPath>
</text>
</svg>
The text will follow the shape of the path, creating interesting visual effects. You can control the position of the text along the path using the startOffset
attribute, which accepts a length or percentage value.
Adding text to your SVG graphics opens up many possibilities for creating informative and engaging visualizations, charts, or diagrams. With the various formatting and styling options available, you can customize the text to match your design needs.
Transforming and Animating SVG
SVG lets you transform and animate elements to create engaging and interactive graphics. You can apply transformations like translation, rotation, and scaling to elements, animate them using SMIL (Synchronized Multimedia Integration Language), or make them interactive with JavaScript.
To transform an SVG element, use the transform
attribute. The attribute accepts various transformation functions:
Function | Description |
---|---|
translate(x, y) |
Moves the element horizontally by x units and vertically by y units. |
rotate(angle) |
Rotates the element by the specified angle (in degrees) around its origin. |
scale(x, y) |
Scales the element horizontally by x and vertically by y . If only one value is provided, it scales uniformly. |
You can combine multiple transformations by listing them space-separated within the transform
attribute:
Example: Combining multiple transformations
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<rect x="50" y="50" width="100" height="100" fill="blue" transform="translate(25, 25) rotate(45) scale(0.5)" />
</svg>
SVG also supports animating elements using SMIL. To create an animation, use the <animate>
element inside the element you want to animate. Specify the attribute to animate using the attributeName
attribute, and set the starting and ending values with the from
and to
attributes. You can control the duration and timing of the animation with the dur
and begin
attributes:
Example: Animating width using SMIL
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<rect x="50" y="50" width="100" height="100" fill="blue">
<animate attributeName="width" from="100" to="150" dur="2s" begin="0s" repeatCount="indefinite" />
</rect>
</svg>
This example animates the width of the rectangle from 100 to 150 over a duration of 2 seconds, repeating indefinitely.
You can animate various attributes like x
, y
, width
, height
, fill
, opacity
, and more. SMIL also provides other animation elements like <animateTransform>
for animating transformations and <animateMotion>
for animating an element along a path.
To make SVG elements interactive, you can use JavaScript to listen for events and manipulate the elements. SVG elements support common events like click
, mouseover
, mouseout
, and more. You can attach event listeners to elements using JavaScript and modify their attributes or styles based on user interactions:
Example: Interactive SVG using JavaScript
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<rect id="myRect" x="50" y="50" width="100" height="100" fill="blue" />
<script>
const rect = document.getElementById('myRect');
rect.addEventListener('click', function() {
this.setAttribute('fill', 'red');
});
</script>
</svg>
You can also use JavaScript libraries like D3.js or Snap.svg to simplify working with SVG and create complex animations and interactions.
By using transformations, animations, and interactivity, you can bring your SVG graphics to life and create engaging user experiences. Experiment with these techniques to add movement, responsiveness, and visual interest to your SVG-based projects.
SVG Filters and Effects
SVG provides a set of filters and effects that let you add visual changes to your graphics. With filters, you can create blur, drop shadow, and lighting effects, while masking and clipping help you control the visibility of elements. SVG also supports blending modes for creating visual combinations.
One filter effect is the Gaussian blur, which softens the edges of an element. To apply a blur effect, use the <filter>
element with a <feGaussianBlur>
primitive. Set the stdDeviation
attribute to control the amount of blur:
Example: Gaussian Blur Effect
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<defs>
<filter id="blurFilter">
<feGaussianBlur stdDeviation="5" />
</filter>
</defs>
<rect x="50" y="50" width="100" height="100" fill="blue" filter="url(#blurFilter)" />
</svg>
Another effect is the drop shadow, which adds a shadow behind an element. Use the <feDropShadow>
filter primitive to create a drop shadow. Specify the dx
and dy
attributes for the shadow offset, stdDeviation
for the blur amount, and flood-color
for the shadow color:
Example: Drop Shadow Effect
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<defs>
<filter id="dropShadowFilter">
<feDropShadow dx="4" dy="4" stdDeviation="4" flood-color="black" />
</filter>
</defs>
<rect x="50" y="50" width="100" height="100" fill="blue" filter="url(#dropShadowFilter)" />
</svg>
SVG also supports lighting effects, which can add depth and realism to your graphics. Use the <feDiffuseLighting>
or <feSpecularLighting>
filter primitives to create lighting effects. These primitives require a light source, such as <fePointLight>
or <feDistantLight>
, and a lighting-color attribute to specify the light color:
Example: Lighting Effects
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<defs>
<filter id="lightingFilter">
<feDiffuseLighting in="SourceGraphic" lighting-color="white">
<fePointLight x="100" y="100" z="50" />
</feDiffuseLighting>
</filter>
</defs>
<rect x="50" y="50" width="100" height="100" fill="blue" filter="url(#lightingFilter)" />
</svg>
Masking and clipping are techniques for controlling the visibility of elements. A mask is an alpha channel that determines the opacity of an element, while a clipping path defines a region outside of which elements are cut off. To create a mask, use the <mask>
element and define the mask content using other SVG elements. Reference the mask using the mask
attribute:
Example: Masking Effect
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<defs>
<mask id="myMask">
<rect x="0" y="0" width="200" height="200" fill="white" />
<circle cx="100" cy="100" r="50" fill="black" />
</mask>
</defs>
<rect x="50" y="50" width="100" height="100" fill="blue" mask="url(#myMask)" />
</svg>
For clipping, use the <clipPath>
element to define the clipping region and reference it using the clip-path
attribute:
Example: Clipping Effect
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<defs>
<clipPath id="myClip">
<circle cx="100" cy="100" r="50" />
</clipPath>
</defs>
<rect x="50" y="50" width="100" height="100" fill="blue" clip-path="url(#myClip)" />
</svg>
SVG supports blending modes, which determine how the colors of overlapping elements combine. Use the mix-blend-mode
attribute to set the blending mode for an element. Some common blend modes include multiply
, screen
, overlay
, and darken
:
Example: Blending Modes
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<rect x="50" y="50" width="100" height="100" fill="blue" />
<circle cx="100" cy="100" r="50" fill="red" mix-blend-mode="multiply" />
</svg>
By using filters, effects, masking, clipping, and blending modes, you can add visual richness and depth to your SVG graphics. Experiment with these techniques to create designs that capture your audience's attention.
Embedding SVG in HTML
You can embed SVG graphics into your HTML documents in several ways, each with its own advantages and use cases. The three main methods are using the <img>
tag, inline SVG, and SVG as a background image.
One of the simplest ways to embed an SVG image is using the <img>
tag. You can reference an external SVG file in the src
attribute, just like you would with other image formats like JPEG or PNG:
Example: Using the <img>
tag
<img src="image.svg" alt="SVG Image" width="200" height="200">
Using the <img>
tag is good for when you want to keep your SVG code separate from your HTML and treat the SVG as a regular image file. However, this method doesn't let you style or script the SVG from your HTML.
If you want more control over your SVG and the ability to style and script it, you can use inline SVG. This means placing the SVG code directly into your HTML document:
Example: Using inline SVG
<body>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<rect x="50" y="50" width="100" height="100" fill="blue" />
<circle cx="100" cy="100" r="50" fill="red" />
</svg>
</body>
Inline SVG lets you use CSS to style the SVG elements and JavaScript to interact with them, just like you would with other HTML elements. This method is good for when you want to create dynamic, interactive SVG graphics that are tightly integrated with your web page.
You can also use SVG as a background image in CSS. Reference the SVG file in the background-image
property or the background
shorthand property:
Example: Using SVG as a background image in CSS
<div class="background"></div>
<style>
.background {
width: 200px;
height: 200px;
background-image: url('image.svg');
background-size: cover;
}
</style>
Using SVG as a background image is helpful when you want to add decorative graphics to your web page without adding them to your HTML markup. You can apply CSS properties like background-size
, background-position
, and background-repeat
to control how the SVG background is displayed.
When deciding which method to use, think about your specific needs:
Method | Use Case |
---|---|
<img> tag |
Display an SVG image without styling or scripting it |
Inline SVG | Create dynamic, interactive SVG graphics that are part of your page content |
SVG as background image | Add decorative graphics to your web page without adding them to your HTML markup |
SVG Accessibility
When creating SVG graphics, it's important to consider accessibility to make sure your content can be understood and navigated by all users, including those with disabilities. SVG provides several features that can help improve accessibility, such as the <title>
and <desc>
elements, ARIA roles and attributes, and other best practices.
The <title>
element lets you provide a brief, descriptive title for an SVG element. This title is not visually displayed but can be read by screen readers to help users understand the purpose of the element. Place the <title>
element as the first child of the element it describes:
Example: Using the <title> element
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40">
<title>Circle</title>
</circle>
</svg>
The <desc>
element allows you to provide a more detailed description of an SVG element. Like the <title>
, the description is not visually rendered but can be accessed by screen readers and other assistive technologies. Place the <desc>
element after the <title>
element:
Example: Using the element
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40">
<title>Circle</title>
<desc>A blue circle with a radius of 40 units, centered at (50, 50)</desc>
</circle>
</svg>
ARIA (Accessible Rich Internet Applications) roles and attributes can also be used to enhance the accessibility of SVG elements. ARIA roles define the purpose or type of an element, while ARIA attributes provide additional information about the element's state or properties.
Example: Using ARIA roles and attributes
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" role="button" tabindex="0">
<title>Click me</title>
</circle>
</svg>
Other accessibility best practices for SVG include:
Best Practice | Description |
---|---|
Provide alternative text | Use the <title> and <desc> elements or the aria-label and aria-labelledby attributes to provide alternative text for SVG images. |
Ensure sufficient color contrast | Ensure sufficient color contrast between foreground and background elements to make the graphics readable for users with visual impairments. |
Use semantic elements | Use semantic elements and meaningful element IDs and class names to help convey the structure and purpose of the SVG content. |
Test with assistive technologies | Test your SVG graphics with screen readers and other assistive technologies to ensure they are accessible and provide a good user experience. |
SVG Optimization and Performance
When using SVG graphics on your website, it's important to optimize them for performance to make sure your pages load fast. Some ways to improve SVG performance are minimizing the file size, using SVG sprites, and following other performance considerations.
One key way to optimize SVG is to reduce the file size. SVG files can contain a lot of unnecessary data, like metadata, comments, and extra whitespace, that can add to the file size. To minimize the file size, you can:
Optimization Technique | Description |
---|---|
Remove unnecessary elements, attributes, and comments | Eliminate any elements, attributes, or comments that are not needed for the SVG to function properly. |
Simplify paths and shapes | Reduce the number of points and combine similar elements to create simpler paths and shapes. |
Use shorter, meaningful names for IDs and classes | Choose concise and descriptive names for IDs and classes to keep the SVG code clean and manageable. |
Compress the SVG file | Use GZIP or another compression method to reduce the file size of the SVG. |
There are also tools like SVGO (SVG Optimizer) that can automate the process of optimizing SVG files.
Another technique for improving SVG performance is using SVG sprites. A sprite is a single file that contains multiple SVG elements, each identified by a unique ID. Instead of loading many individual SVG files, you can load the sprite once and display different parts of it as needed, which reduces the number of HTTP requests and speeds up page loading.
To create an SVG sprite, combine your individual SVG files into one file and give each SVG element a unique ID. Then, reference the sprite in your HTML using the <use>
element and the ID of the SVG you want to display:
Example of SVG sprite usage
<svg>
<use xlink:href="sprite.svg#icon-1"></use>
</svg>
There are also some general performance considerations to keep in mind when using SVG:
- Only use SVG for graphics that need to be scalable or interactive. For simple images, raster formats like JPEG or PNG may be more suitable.
- Be mindful of the number and complexity of SVG elements on a page. Very complex graphics with many elements can slow down rendering.
- Avoid using SVG filters and effects excessively, as they can be performance-intensive, especially on mobile devices.
- Cache SVG files to reduce load times for repeat visitors.
- Serve SVG files with gzip compression to reduce their transfer size.