Jump to content
Slate Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate Marble
Slate Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate Marble
Sign in to follow this  
Rss Bot

The complete guide to SVG

Recommended Posts

Scalable Vector Graphics are now universally supported across all browsers (desktop and mobile) . Here's our guide to what they are, and how to design and implement them in your web design work.

First, here are eight reasons why you should be using SVG:

01. Vectors are crisp

SVG uses a coordinate plotting system to plot points and connect them to draw lines, shapes or paths. Vector graphics are drawn using mathematics, meaning they're sharp and crisp, not pixelating like other image formats, making them great for logos, icons and illustrations.

SVG has a number of other features, too – with filters, patterns, gradients and masking and the 'viewBox' property for framing the scene – and they're all animatable. SVG is extremely versatile and supported by all browsers going all the way back to IE9.

02. It's got a navigable DOM

SVG inside the browser has its own DOM. SVG is treated as a separate document by the browser and then positioned inside the normal DOM of the page. This is important for the 'viewBox' property as we can draw our image on a canvas of any size, but then display it in browser at another, all without updating the properties inside the SVG. This separate, navigable DOM is also how we interact with elements inside SVG using CSS and Javascript.

03. It's accessible

SVG has tags built specifically for accessibility, the main one being the '<title>' tag. The title tag along with the '<desc>' tag should be used to provide fallback content for screen readers. 

The contents of these tags won't be displayed by the browser but they will be exposed to the browsers accessibility API. You can (and should) also use the correct ARIA properties where applicable, for example if you're hiding an SVG element.

04. It's resolution independent and responsive

9ukNvFtyFCpp8pHd27Visg.jpg

The classic Coca-Cola logo rendered at different adaptive sizes

Due to the vector nature of SVG, the image is resolution independent. The image looks crisp on any display from the beautiful ~285 ppi pixel density displays found on new smart phones to the ~85 ppi of standard monitors. 

Using SVG we can stop creating '@2x.png' images (unless you need to support IE8) and create one file for all of our icons (more on this later). SVG images can also be scaled the same way we scale all other elements in responsive design. 

05. It's animatable

Elements inside SVG can be animated to create some truly amazing interactive experiences or the animation can be used to add nice little touches to an interface, image or icon. 

Animation can be created using CSS, the Web Animations API in Javascript or using the SVG's '<animate>' tag. SVG animation is at an interesting point in development. Google deprecated SMIL – SVG's animate tag – in Chrome 45 in favour of CSS animations and the Web Animations API but has since suspended the deprecation. 

06. It's style-able 

Using class names or ID's you can style elements inside of SVG only using slightly different properties to those we would normally use; instead of 'color' we use 'fill', and instead of border we use 'stroke`. There are some limits to styling SVG these come from how you're using SVG in the page. If you use an SVG as an image tag you will not be able to style the elements inside in Internet Explorer, there is, however, a polyfill – svg4everybody – which will fix this problem.

07. It's interactive 

Using Javascript we can interact with elements inside of SVG, thanks to the navigable DOM. This allows us to create interactive elements using SVG the same way we would with HTML and CSS. 

We can also apply animations through Javascript using the new Web Animations API allowing both simple and complex interactions and animations to be programmed. There's also a number of Javascript libraries we can use, which have been created to speed up SVG workflows.

08. Its file sizes can be small

PiBVuscPQcw7cdrPPLxpU6.jpg

A combination of intelligent hand-editing and post-production optimisation can reduce SVG file sizes markedly

Due to the vector nature of SVG (being an image drawn from a set of coordinates) their file sizes when optimised are small when compared to almost any other image file type. 

There are a number of ways to optimise SVG from command line tools to manually removing points and groups but SVGOMG has a GUI and plenty of options to tweak showing you visually the changes being made during optimisation.

Since SVG's can be responsive, animated and complex there's no reason you shouldn't use them for big hero images or images on a blog post or other online media.

Next: How to use SVG

How to use SVG

There are a number of ways to use SVG on the web; browser support is very good with support only lacking in IE8 and below, and really early versions of the Android browser. It's safe to use it, so we should be using it! By using SVG you're sending the instructions of how to draw something to the browser instead of the drawn thing itself.

cEARjD7SFSR9PPE55L5b7k.jpg

There are plenty of sites where you can source SVG images; if you're after icons or logos, try SVG Porn

The image tag

You can embed an SVG image into the page the same way you do any other image using the HTML image tag;

Embedding the image into the page this way will assume the size of original SVG file unless you specify a width and height attribute in HTML or via CSS. Using the image tag is good for logos and other content when you need screen readers to have access to the alt attribute. You can provide fallbacks for when SVG isn't supported using Modernizr to swap in a PNG. 

CSS Background Image

You can also embed an SVG image into the page in CSS, using the same method as you would to attach any other kind of image to an element;

By using the SVG this way we can take advantage of the other CSS background properties allowing us to size, position and repeat our image as the background of an element.

To provide support we can use a trick in the way CSS is parsed by the browser and provide a fallback PNG right before we include our SVG.

Inline SVG

SVG can be written inline, straight into the document using the SVG tag;

Since SVG is scalable (it's in the name) if we provide the tag without the width and height attributes the SVG will grow to the size of the container. By writing our SVG into the page we could remove the fill from the inline SVG and style it in CSS;

Fallbacks for using this method again rely on providing a PNG fallback and using Modernizr to detect support. The only other disadvantage is that inline SVG – being markup – will not be cached by the browser.

As an object

You can also embed SVG as an object or iframe which will utilise the browsers cache but will maintain the style-ability of the SVG.

Next: Writing SVG for the web

Writing SVG for the web

SVG demo by Vincent Hardy

: a synchronised audio and graphic animation combining SVG, JavaScript and a simulated 'camera'

As SVG is an XML language it looks very similar to HTML, where tags are nested, and it is written using those recognisable angled brackets.

Even though most of the time you'll likely be using software to output your SVGs, it's still worth learning the basic tags. Learning these tags will allow you optimise and make quick adjustments to any element in your SVG. You'll likely need this knowledge to utilise filters, effects, patterns, masks and animation.

SVG gives designers the abilities they once had with the soon-to-be-defunct Flash. But, this time around, the content is accessible to screen readers and supported natively within the browser.

Basic Shape Tags

SVG has tags for all of the basic shapes; rectangles and squares ('<rect>'), circles ('<circle>'), ellipse ('<ellipse>'), line ('<line>'), polyline ('<polyline>'), polygon ('<polygon>') and path ('<path>'). 

These tags are used to create most elements inside SVG.

Text Tag

The text tag ('<text>') is used to create text inside of SVG, which will be selectable and accessible just like any text in HTML. 

Accessibility Tags

The title ('<title>') and description ('<desc>') tags are specifically for providing accessibility content and will not be rendered on the screen.

Group Tag

The group tag ('<g>') is very useful in SVG. This tag is used to group elements together allowing you to add class names and apply animations, filters, patterns and effects to a group of elements.

Defs Tag

The defs tag ('<defs>') is used to define elements for later reuse. This is where you create patterns, filters and masks to be reused later. This is also used to create icon systems.

How to set SVG up for the web

2hr5gxN5UQtTRqmJJZYPPb.jpg

from Vincent Hardy combines SVG, web fonts and the audio tag to create a visually pleasing animation of lyrics

01. Export the SVG

Export the file from your graphics editor, we'll be using a simple landscape drawing in SVG created by Steven Roberts. Both Sketch and Illustrator will export images as an SVG as well as many other editors.

02. Trim the fat

After you've exported the file open it in your choice of IDE or text editor. From here you can remove the unwanted tags and comments and update the accessibility tags.

03. SVGO

SVGO is a optimisation tool that runs on the command line, this tool is really useful and has a number of options available to the user to choose how to best optimise any given SVG.

04. SVGOMG

SVGOMG shows you your SVG optimisations as they happen

The only problem with SVGO is that you cannot see if the changes you're making during optimisation are making visual changes to the image. SVGOMG runs in the browser and visually shows you the changes you're making.

05. Optimise

Using the web app you need to import the SVG either the file or by copying the markup from the editor and pasting it in. From here you're presented with a multitude of options allowing you to quickly turn them on and off while visually seeing the changes being made.

06. Export the file again

The more you play with SVG and depending on your intentions for any particular SVG you will want the settings to differ slightly. The editor shows you how much the file size has changed right next to the download button. Once you're happy with the settings click the download button to export the file.

Next: SVG filters and effects

SVG filters and effects

pbXmR7NHGVWXyMjnwEAVte.jpg

Microsoft has created a site where you can try out SVG filters and effects live

Filters in SVG are usually created inside the '<defs>' element and given an ID for referencing later, this can be as an attribute on an SVG element or defined in CSS.

Filters in SVG are powerful and can be used to produce some truly stunning effects! In order to use a filter in SVG we use the '<filter>' element. Inside of this element we have a number of tools available to us; Blend, Colour Matrix, Component Transfer, Composite, Convolve Matrix, Diffuse Lighting, Displacement Map, Flood, Gaussian Blur, Image, Merge, Morphology, Offset, Specular Lighting, Tile and Turbulence. These are called filter primitives. An SVG filter is made up using a number of these filter primitives.

A filter primitive has one or two inputs and one output. For the input we have a number of options available to us to due to browser support the main two are; 

SourceGraphic The whole source graphic (can be text, shapes, path, etc), another element inside SVG complete with colours, fills and other styles.

SourceAlpha Only the opaque parts of the alpha channel from the source graphic (essentially the element but filled black without any styles).

We'll take a look at a few of the filter primitives available to us below and cover basic usage. Filters in SVG can be complicated, we'll only be covering the basics.

Blur

The blur filter primitive can be used to apply blurring to an element. The filter primitive is created using the '<feGaussianBlur>' element and the amount of blurring is controlled using the 'stdDeviation' attribute.

<feGaussianBlur stdDeviation="25" />

Offset

The offset filter primitive can be used to position elements at an offset of their source. The filter primitive is created using the '<feOffset>' element and controlled using the 'dx' and 'dy' attributes. These attributes specify the x and y amounts of the offset. This filter is often combined with blurring to create a drop shadow.

<feOffset dx="15" dy="15" />

Colour Matrix

The colour matrix filter primitive can be used to perform a number of colour transformations. The filter primitive is created using the '<feColorMatrix>' element and controlled using the 'type' and 'values' attributes.

<feColorMatrix type="hueRotate" values="171" />

Turbulence

The turbulence filter primitive can be used to generate noise and artificial textures. The filter primitive is created using the '<feTurbulence>' element and controlled using a number of attributes.

<feTurbulence type="turbulence" baseFrequency="0.05" numOctaves="2" result="turbulence"/>

Morphology

The morphology filter primitive can be used to erode or dilate an element. The filter primitive is created using the '<feMorphology>' elements and is controlled using the 'operator' and 'radius' attributes. This filter is often used for thinning or flattening. 

<feMorphology operator="erode" radius="1"/>

<feMorphology operator="dilate" radius="1"/>

How to create a filter

01. Find the moon

In order to apply our filter once we've created it we need to find the moon in the DOM. We find the correct element using devtools then apply a class name to it.

02. Create the filter

Inside the 'defs' tag we can create our filter using the filter element. Inside of our filter we'll use the feTurbulence element to generate our noise.

03. Create a pattern element

In order to use our noise filter as a fill for an element we create a pattern element. We create this inside of the 'defs' tag making sure to give the pattern a unique ID.

04. Drawing the pattern

Inside of our pattern element we need to crate some two rectangles. We'll start by creating the background. 

05. Finish the pattern

After our background rectangle we create a second one this time applying the filter and changing the opacity.

06. Apply pattern to the moon

Now we've created the filter and applied it to our pattern, the only thing left to do is apply it to our chosen element. In this case we'll apply it using CSS but we could just as easily apply the filter inline.

Next: Add animation to SVG

Web Animations API

Animation on the web has always been possible through the use of Flash, jQuery, CSS or SMIL. The Web Animations API aims to achieve a mixture of all of these by using the power and simplicity of CSS animations and the flexibility of Javascript to interact with elements on the page, including SVG, leaving the browser to deal with performance. Whether you're animating in CSS or Javascript, they will both harness the power of the same underlying engine.

Complex animation

For simple animations the Web Animations API in Javascript is sufficient and although it is capable of complex animations there are a number of libraries you can use to speed up your workflow and again easier cross browser support. The standard is GSAP; having been around for ten years now, these libraries are mature and battle tested with many award winning websites and animations utilising them.

How to create SVG animation

01. Edit the SVG

In order to target the stars to animate them we'll need to edit the SVG to add a class to the group containing the stars. We can identify this group using devtools.

02. Set the default opacity

If we were to leave the opacity set to the default of 1 the stars would all be bright to begin with. Setting them to '0.3' will fade them by default and set a default opacity.

03. Create the animation

Next, we need to create our animated blinking effect. Since we've already set the default opacity our keyframe animation will only need to change at the middle point.

04. Apply the animation

In order to apply animation we target the stars group and then the path's inside of it and apply our animation. This will apply the same animation which is fine except they all blink at the same time.

05. nth:child

To stop all of the stars blinking at the same time we can use nth-child to target groups of stars. We will use '8n' in order to target every eighth star.

06. Delays

Since we're only targeting every 8th star with our nth-child selector we need to provide the remaining stars using the nth-child and then taking a number away all the way up to '- 7'. Each time we do this we increase the delay of the animation to stagger the blinking.

Next: The power of sprites

The power of sprites

SVG allows us to create icons in a file format that is resolution independent, which is awesome, but due to the limitations of the HTTP protocol we don't want to make another file request for every icon in our website, this will soon be changing with the HTTP/2 protocol.

In order to avoid having to make a separate request for each icon we can go back to our old friend the sprite, except this time in SVG. To create a sprite in SVG we use the '<symbol>' tag and apply an ID for referencing later and the 'viewBox' attribute for defining the canvas size. Inside of the symbol icon we create our shapes, text and any other elements that make up our icon. Inside of the symbol tag we can also add additional elements for accessibility, such as the '<title>' and '<desc>' tags. We create our icons inside of a '<defs>' tag in order to define them for later use and to ensure they're not output onto the page. 

There are a number of ways you can create sprites in SVG. They can be created using vector software – such as Adobe Illustrator or Sketch – by simply placing the icons onto an art board and exporting the file as an SVG. However, the code they produce needs some editing in order to use as an icon system. Another way is to create an icon system manually. This isn't too difficult and you have complete control over the markup. SVG sprites can also be incorporated into build systems like gulp or grunt, whereby you choose a folder containing SVG files and configure the build to output a single SVG sprite. 

Once we've created or generated our SVG sprite there's a couple ways we can use it. We could copy the contents of the file and put it at the top of our page, this is called inlining or if we're using php we could use the 'file_get_contents()' function to include the file globally. The only downside is that the file will not be cached because it's treated as code by the browser and not an image. 

How to create an SVG sprite

01. Create the framework

For this tutorial we'll be placing the SVG inside the body of the website, but we'll see how it works using the file externally. The basic code requires an SVG tag and the empty '<defs>' tag.

02. Create our symbol

Inside the '<defs>' tag we'll create our first icon using the symbol tag, we need to give the icon the ID and 'viewBox' attributes. Inside we'll provide a title and shapes to make up our icon.

03. Repeat

Now we've created our first icon we'll do the same for the rest of them. Making sure to provide a unique ID and include the 'viewBox' attribute.

04. Use the icon

Now we've defined all of our icons, we can pull them out and use them on the page wherever we need them.

In order to use the sprite as an external file we need to update the use element to reference the file and then the ID.

05. Class names

We can repeat the previous step in order to output all of our icons. If we wrap an '<a>' tag around the icon and add classes to both the '<a>' and '<svg>' we can style our icons with CSS.

06. The CSS

Now we have our icons and they have individual class names we can apply different fill colours to each of our icons.

This article was originally published in issue 267 of Web Designer, the creative web design magazine – offering expert tutorials, cutting-edge trends and free resources. Subscribe to Web Designer here.

Related articles:

View the full article

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

×