How to handle SVG

Some time ago I’ve realised that it’s hard to find a quick and practical information about SVG format on the internet. There are thousands of huge articles/websites explaining every aspect of working with SVG or just simple examples on how to implement this format in a specific way. However those articles can be hard to understand for a newbie. In this article I’ll try to show you what make this format awesome and a few SVG related solutions I use in everyday work at Assertis.

At the beginning I will explain what is an SVG. SVG stands for Scalable Vector Graphic. It’s an XML based markup that contains two-dimensional vectors which your browser renders as images. XML based means that every element is available within the SVG DOM. You can attach JavaScript event handlers to an element and use CSS to change specific parts of the image. Vectors in SVG can be represented as rectangles, circles, polygons, text or almost anything. To be more specific, I mean anything that you can create with vector graphic tool on the two-dimensional artboard. SVGs also have W3C recommendation and that’s a cool thing though.

SVG is probably the most powerful image format that you can currently use in web projects. It allows you to manipulate its properties with code. Images with fixed sizes such as .png.jpg or .gif are commonly used on the web, but their inherently static nature conflicts with a modern direction in which the web evolves. Those formats are fundamentally not responsive. You can’t resize them without losing quality or change their colors without using graphic tools such as Adobe Photoshop. Especially these days it can be quite frustrating to build a website with the use of static images. You would need to make a few copies of each image in different sizes just to display them properly on different screens with a different device pixel ratio. With SVG you create just one image which will scale to a required size or a device pixel ratio without losing its quality. What’s more you can change its colors, shapes or even animate it if you like.

In a nutshell, SVG:

  • Is resizable without losing quality (of course to some level of downsizing)
  • Looks sharp on all devices (even Retina)
  • Properties can be manipulated from the code level
  • It can be animated (I will explain this later in this article)
  • If it’s saved as a file it can be compressed well

So let’s get to practice on using of this lovely format.


How to create and SVG file?

The best and probably the fastest way to create SVG is using vector graphic tools. Currently, the most popular tools are Adobe Illustrator, Sketch and Affinity Designer. Personally, I prefer Adobe Illustrator, mainly because I love doing illustrations besides working on web projects, and I’m just used to it for years. However, it’s worth keeping in mind that every tool have its pros and cons, for example Adobe Illustrator generates unnecessary code / stamp inside our SVG which can affect the performance and the overall loading time of the site. You can also use online SVG creators if you do not want to pay for expensive desktop software.


How to write and SVG?

If you don’t like designing software, and all your life is code, then probably writing SVG on your own will be the best solution for you. However, it might be a bit harder with more complex shapes. First, let’s see how to write SVG code for a simple rectangle.

HTML
<svg width="200" height="150">
<rect width="200" height="150" style="fill:rgb(22,45,128);stroke-width:1;stroke:rgb(41,246,183)" />
</svg>

As you can see in the example above, SVG image is made from two elements. First, we defined <svg> element in which we can place rectangles, circles, polygons, images etc. Inside the element, we placed <rect> tag which stands for rectangle. Next, we specified the width of 200 pixels and the height of 150px of the rectangle, the same way as we do it with <img> elements. We added some SVG specific styles like fill color and stroke. There are tons of other styles you can apply to elements! You can read about all of them in MDN Web Docs.

Now you can see that creating an SVG is based on typing a few lines of code and no special software is required to do it.


Displaying SVG on my website

There are a couple of different ways to display an SVG. For example, it can be saved as file with .svg extension or it can be placed in HTML in an inline way. I will try to explain 3 most common ways on how to place SVG on your website.

SVG as background-image in CSS
You can use .svg file to be displayed as CSS background-image.
In this case, while you’re creating your file in vector graphic tool, write down the sizes (width, height) of the artboard on which you drawn the shape.

HTML
<span class=”train”></span>
CSS
.train {
display: block;
width: 130px;
height: 166px;
background-image: url(train-icon.svg);
background-size: 130px 166px;
text-indent: -9999px;
}

When using this technique, it’s worth remembering to set background-size with the sizes you wrote down from vector graphic tool. Otherwise you will see only the part of the image. The aspect ratio of original .svgfile has to be kept.

SVG as <img> element
You can use .svg file to be displayed as <img> element.

HTML
<img src="train-icon.svg" alt="train on tracks">

This case is similar to the background-image case. But this time, set the <img>width and height attributes as dimensions of your .svg file artboard.

While using the above two methods, parameters can’t be controlled from CSS level. That’s why, the third method might be a better choice.

Placing SVG inline in HTML
SVG code must be placed inside the <body> section like any other HTML element. To get your SVG code, open the file with any text editor and just copy the code. Before pasting your SVG code, optimize it. As I wrote earlier, graphic tools can add lines of code including doctype, comments, notes and any other kind of unwanted junk. Try not to forget to remove those lines from your file before copying the code to HTML.

HTML
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 130 166">
<style type="text/css">
.dark-line{fill:none;stroke:#162d80;stroke-width:6;}
.light-line{fill:none;stroke:#29f6b7;stroke-width:6;stroke-linecap:round;stroke-linejoin:round;}
</style>
<path class="dark-line" d="M116,136H14c-5.5,0-10-4.5-10-10V14C4,8.5,8.5,4,14,4h102c5.5,0,10,4.5,10,10v112C126,131.5,121.5,136,116,136z"/>
<line class="dark-line" x1="4" y1="27" x2="126" y2="27"/>
<line class="dark-line" x1="4" y1="92" x2="126" y2="92"/>
<line class="dark-line" x1="65" y1="27" x2="65" y2="92"/>
<line class="light-line" x1="40" y1="16" x2="88" y2="16"/>
<circle class="light-line" cx="30" cy="110" r="9"/>
<circle class="light-line" cx="100" cy="110" r="9"/>
<line class="dark-line" x1="100" y1="136" x2="126" y2="162"/>
<line class="dark-line" x1="30" y1="136" x2="4" y2="162"/>
</svg>

As you can see above it can look messy, but really it’s easier than it looks. I’ve created two CSS classes for elements in SVG .dark-line and .light-line. You can style those as normal HTML elements, using special SVG CSS properties. Also you can use CSS special filters. Mainly we use only a few properties on SVG:

  • fill — it is similar to CSS background-color but here you fill in only the shape with color.
  • stroke — it is the color of the stroke around our shape
  • stroke-width — it is the width of our stroke set in pixels ;)
  • stroke-linecap — it’s the style of anchor points of the line. It can have 3 effects “butt”, “square” or “round
  • stroke-linejoin — it’s the style of edges where lines are joined. It can also have 3 effects “miter”, “round” or “bevel

There are a lot more of properties to use and if you’d like to know more about them, check out MDN or W3Schools. You can also poke me via email and maybe I will write an article about it.


Animated SVG?

At this point you know how to create SVG and how to place it on your website. So now is the time to write a few words about animating an SVG. Once again, there are a few methods of doing so, but today I will show you how to animate the SVG file inside itself. We can add animation via CSS inside the .svg file or in inline .

First we create the animation effect in CSS. As an example, I will create a stroke drawing animation.

CSS
@keyframes stroke-draw {
from {
stroke-dashoffset: 1000;
}
to {
stroke-dashoffset: 0;
}
}

Next, we should create classes for our SVG elements. I will use the example created earlier. We have already created classes .dark-line and .light-line. Now, we can assign our animation to those classes this way:

CSS
.dark-line { 
fill: none;
stroke: #162d80;
stroke-width: 6;
stroke-dasharray: 1000;
stroke-dashoffset: 1000;
animation: stroke-draw 3s linear alternate infinite;

}
.light-line {
fill: none;
stroke: #29f6b7;
stroke-width: 6;
stroke-linecap: round;
stroke-linejoin: round;
stroke-dasharray: 1000;
stroke-dashoffset: 1000;
animation: stroke-draw 5s linear alternate infinite;

}

Then we can optimize the code and the end-result code should look like this:

HTML
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 130 166">
<style type="text/css">
@keyframes stroke-draw{from{stroke-dashoffset:1000;}to{stroke-dashoffset:0;}}
.dark-line{fill:none;stroke:#162d80;stroke-width:6;stroke-dasharray:1000;stroke-dashoffset:1000;animation:stroke-draw 5s linear alternate infinite;}
.light-line{fill:none;stroke:#29f6b7;stroke-width:6;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:1000;stroke-dashoffset:1000;animation: stroke-draw 5s linear alternate infinite;}
</style>
<path class="dark-line" d="M116,136H14c-5.5,0-10-4.5-10-10V14C4,8.5,8.5,4,14,4h102c5.5,0,10,4.5,10,10v112C126,131.5,121.5,136,116,136z"/>
<line class="dark-line" x1="4" y1="27" x2="126" y2="27"/>
<line class="dark-line" x1="4" y1="92" x2="126" y2="92"/>
<line class="dark-line" x1="65" y1="27" x2="65" y2="92"/>
<line class="light-line" x1="40" y1="16" x2="88" y2="16"/>
<circle class="light-line" cx="30" cy="110" r="9"/>
<circle class="light-line" cx="100" cy="110" r="9"/>
<line class="dark-line" x1="100" y1="136" x2="126" y2="162"/>
<line class="dark-line" x1="30" y1="136" x2="4" y2="162"/>
</svg>

Now save this code as file with .svg extension and launch it in the browser you should see a nice animation of your SVG file. Cool, isn’t it?


Practical hints

  • While creating an SVG in any vector graphic tool try to put your shape anchor points on the pixel grid so each point x / y coordinates are a whole number — NOT an decimal. It can help you in getting rid of blurry edges, lines.
  • Remember to optimize your SVG before placing it on web. Peter Collingridge created handy tool for this task http://petercollingridge.appspot.com/svg-optimiser
  • If you create SVG in vector graphic tool and save it as .svg file then remember to leave 1px margin of the artboard around the shape. Some of the browsers might cut the part of your svg image.

I’ve tried to show you why designers and developers prefer using SVG over PNG and JPG files. I hope that you will find information in this article useful and you will be able to use this in your own projects.
Cheers!

RESOURCES
https://developer.mozilla.org/en-US/docs/Web/SVG
https://www.w3schools.com/graphics/svg_intro.asp
https://css-tricks.com/

Author: Patryk Bartosik