SVG In HTML Introduction

Overview

This article and its associated example shows how to use inline SVG to provide a background picture for a form. It shows how JavaScript and CSS can be used to manipulate the picture in the same way you would script regular XHTML. Note that the example will only work in browsers that support XHTML (not HTML) and SVG integration.

Discussion

The page is mainly regular XHTML, CSS and JavaScript. The only interesting part is the <svg> element it contains. This element and its children are declared to be in the SVG namespace. The element contains a gradient and two shapes filled with the gradient. The gradient color stops have their colors set by CSS. When the user enters something incorrect into the form, the script sets the invalid attribute on the <body>, and a style rule changes the gradient end-stop color to red. (Another style rule makes an error message appear.)

This approach has the following points in its favor:

We have taken a regular XHTML form that could have been part of an existing Web site, and added an attractive, interactive background

The approach is backwards compatible to browsers that do not support SVG; simply, no background appears in them

It's very simple and performs very well

The picture dynamically sizes itself to the required size in an intelligent way

We can have declarative style rules applying to both HTML and SVG

The same script manipulates both HTML and SVG

The document is entirely standards-based

To add a linked image with DOM methods to an embedded SVG element, one has to use setAttributeNS to set href. Like in the following example:

Details

The viewBox attribute establishes a logical coordinate system which the SVG picture's coordinates are relative to. In this case our picture is laid out in a 100 by 100 viewport.

The preserveAspectRatio attribute specifies that the aspect ratio must be preserved by centering the picture in the available size, sizing to the maximum of the height or width and then cutting off any overflow.

The style attribute pins the SVG element to the background of the form.

Related Links

Working example that works in both Mozilla and in Internet Explorer with Adobe's SVG Viewer installed. (For inline SVG to work in both Firefox and Internet Explorer it is necessary to serve documents with a different Content-Type to each browser. For this reason, if you're behind a proxy server that caches the page, the example wont work in the second browser you load it in because it will receive the wrong Content-Type.)