SVG in HTML5
SVG in HTML
Section titled “SVG in HTML”In modern HTML, you can embed Scalable Vector Graphics (SVG) elements directly into your HTML pages. This allows you to integrate vector graphics seamlessly with other web content.
Embedding SVG Directly Into HTML Pages
Section titled “Embedding SVG Directly Into HTML Pages”Here is an example of a simple SVG graphic embedded in an HTML page:
Sorry, your browser does not support inline SVG.
And here is the HTML code for the example above:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>My First SVG</title></head><body> <h1>My First SVG</h1> <svg width="100" height="100" aria-labelledby="svgTitle" role="img"> <title id="svgTitle">A yellow circle with a green border</title> <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /> </svg></body></html>SVG Code Explanation:
- An SVG image begins with an
<svg>element. It’s good practice to includearia-labelledbyandrole="img"for accessibility, along with a<title>element inside. - The
widthandheightattributes of the<svg>element define the dimensions of the SVG canvas. - The
<circle>element is used to draw a circle. - The
cxandcyattributes define the x and y coordinates of the center of the circle. Ifcxandcyare omitted, the circle’s center defaults to (0,0). - The
rattribute defines the radius of the circle. - The
strokeandstroke-widthattributes control the appearance of the shape’s outline. Here, the circle has a 4px green outline. - The
fillattribute specifies the color inside the shape. We’ve set the fill color to yellow. - The closing
</svg>tag marks the end of the SVG image. Note that elements like<circle />can be self-closing in XML syntax.
Important Note: Since SVG is XML-based, all elements must be properly closed. For elements without content, you can use self-closing tags (e.g., <circle />).
Accessibility Tip: Always include a <title> element within your <svg> to provide a textual description of the graphic for assistive technologies. You can also use the <desc> element for a more detailed description.