Skip to main content

All you need to know about SVG on the web

There are several ways you can use SVG on your webpages, including in CSS and HTML. Read on for an explanation of how you can use SVG in a number of different ways in your designs.

Use the <img> Tag

To embed an SVG via an <img> element, you just need to reference it in the src attribute as you would with any image. You should define a height and width as well, the same as when you add images. Here is an example of what the HTML code looks like:

<img src="circle.svg" alt="a red circle" height="100px" width="100px" />

The advantages to this method are that it is very quick and easy to add. You can also wrap it in an <a> tag to make it a hyperlink like a regular image. You can use CSS to affect the SVG image the same as any other, but you cannot use JavaScript or external CSS to manipulate the content of this image. You can still use inline CSS in the SVG code itself if you edit the SVG code.

Use SVG in CSS

SVG images can be used as background-image in CSS as well, just like PNG, JPG or GIF images. Here is an example of including an SVG image in CSS:

.element { background-image: url(/images/image.svg); }

The advantages of SVG, such as crispness at any size, are retained with this method. You can also do anything a raster graphic can do, like repeat, scale, position and more.

Inline SVG in HTML

You can also open up the SVG file in any text editor, copy the SVG code and paste it into your HTML document. We call this inlining SVG or using it inline. SVG code elements begin and end with the <svg></svg> tags. Here is a simple example of what you could paste into your document:

<svg width="100" height="100">
  <circle cx="50" cy="50" r="40"stroke="black" 
  stroke-width="4"fill="red" />
</svg>

Putting your SVG inline saves HTTP requests and therefore can reduce your loading time. You can assign classes and ids to SVG elements and style them with CSS, either within the SVG or wherever you put the CSS style rules for your HTML document. In fact, you can use any SVG presentation attribute as a CSS property.

Coding SVG

SVG uses an XML-based language for describing vector images. It's a markup language, like HTML, except that you have a wide variety of elements for defining the shapes to create these images, along with effects to apply to these shapes as well.

You can code SVG right along with your HTML in your favourite code editor. You can code them as separate files and include them, or you can code them inline in your HTML. As a simple example, the following code creates a circle and a rectangle:

<svg version="1.1"
     baseProfile="full"
     width="300" height="200"
     xmlns="http://www.w3.org/2000/svg">
  <rect width="100%" height="100%" fill="black" />
  <circle cx="150" cy="100" r="90" fill="blue" />
</svg>

Next page: Making shapes