What is SVG in HTML: Definition, Usage, and Examples
SVG stands for Scalable Vector Graphics and is a way to draw shapes, lines, and images directly in HTML using XML-based code. It lets you create graphics that stay sharp at any size because they use math to draw shapes instead of pixels.How It Works
Think of SVG as a set of instructions for drawing pictures using shapes like circles, rectangles, and lines. Instead of using tiny dots (pixels) like photos, SVG uses math formulas to describe these shapes. This means you can zoom in or out without losing any detail or making the image blurry.
In HTML, you include SVG code inside a special <svg> tag. The browser reads this code and draws the shapes on the screen. It’s like giving the browser a drawing recipe that it follows exactly.
This makes SVG perfect for logos, icons, charts, and any graphics that need to look good on all screen sizes and devices.
Example
This example shows a simple SVG drawing of a red circle inside a square area. You can copy and paste this code into an HTML file and open it in a browser to see the circle.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>SVG Example</title> </head> <body> <svg width="200" height="200" role="img" aria-label="Red circle"> <circle cx="100" cy="100" r="80" fill="red" /> </svg> </body> </html>
When to Use
Use SVG when you need graphics that look sharp on any screen size, such as logos, icons, charts, or simple animations. Because SVG images are made of shapes, they are usually smaller in file size than photos for simple graphics, which helps pages load faster.
SVG is also great when you want to change colors or shapes with code or CSS, making it very flexible for interactive websites.
However, for very complex images like photos, regular image formats like JPEG or PNG are better choices.
Key Points
- SVG uses math to draw shapes, so it scales perfectly without losing quality.
- It is included in HTML using the
<svg>tag. - Ideal for logos, icons, charts, and animations.
- SVG images can be styled and scripted with CSS and JavaScript.
- Not suitable for complex photos, where bitmap images are better.