Skip to content

SVG in HTML5

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.

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 include aria-labelledby and role="img" for accessibility, along with a <title> element inside.
  • The width and height attributes of the <svg> element define the dimensions of the SVG canvas.
  • The <circle> element is used to draw a circle.
  • The cx and cy attributes define the x and y coordinates of the center of the circle. If cx and cy are omitted, the circle’s center defaults to (0,0).
  • The r attribute defines the radius of the circle.
  • The stroke and stroke-width attributes control the appearance of the shape’s outline. Here, the circle has a 4px green outline.
  • The fill attribute 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.