Welcome to our in-depth guide on HTML SVG! In this tutorial, we'll explore the exciting world of Scalable Vector Graphics, learn how to use them in your web projects, and even write some code together. šÆ
SVG stands for Scalable Vector Graphics. Unlike traditional image formats like PNG or JPEG, SVGs are vector-based images that can be resized without losing quality. They're XML-based, meaning they're written in plain text, making them easy to create and edit.
š Note: SVGs are ideal for logos, charts, diagrams, and any other image that needs to scale smoothly.
Let's create a simple SVG. Open your favorite text editor and write:
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>š” Pro Tip: In the above example, we're creating a circle with a center at (50, 50) and a radius of 40 pixels. The stroke attribute sets the color of the circle's border, while fill sets the color inside the border.
To use our SVG in an HTML document, save it as circle.svg and include it like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First SVG</title>
</head>
<body>
<h1>My First SVG</h1>
<svg width="300" height="300">
<!-- Import our SVG -->
<foreignObject width="100%" height="100%">
<img src="circle.svg" alt="SVG Image" />
</foreignObject>
</svg>
</body>
</html>Now, when you open the HTML file in a browser, you should see our circle!
Let's dive into more advanced SVG examples. Here's a simple bar chart using SVG:
<svg width="400" height="200">
<!-- Define the scales -->
<defs>
<linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:#f00; stop-opacity:1" />
<stop offset="100%" style="stop-color:#00f; stop-opacity:1" />
</linearGradient>
</defs>
<!-- Create the bars -->
<rect x="20" y="20" width="30" height="120" fill="url(#gradient)" />
<rect x="70" y="20" width="30" height="60" fill="url(#gradient)" />
<rect x="120" y="20" width="30" height="20" fill="url(#gradient)" />
</svg>š” Pro Tip: In this example, we're creating a linear gradient that changes from red to blue. We're then using this gradient to fill three rectangles, representing a bar chart.
Now it's your turn to create an SVG! Design a simple logo or a diagram and write the SVG code for it. Once you're done, save it as an .svg file and include it in an HTML document, like we did earlier.
What does SVG stand for?