SVG Basics—How to Work with Scalable Vector Graphics

Whenever I talk about responsive images, I mention that where possible, scalable vector graphics are a preferred option to bitmap images. The last time I offered the advice, I realized I didn’t know as much about SVG as I should.

I’ve stumbled through a post or two about SVG, but that’s about as far as my practical knowledge extends. I thought it time to change that. I’d like to begin a series on SVG today. I’ll cover some of the basics over the next few weeks and I’ll revisit SVG throughout the year with additional topics.

What is SVG and Why You Should Use It

Just in case anyone doesn’t know, I want to start at the very beginning and answer two important questions about SVG. What and why?

SVG is an XML based language that’s used for working with 2-dimensional graphics. You can write the code to display simple or complex shapes, lines, and curves or, if you prefer, you can create those shapes, lines, and curves in a vector editing program and have the program export the code.

There are a number of reasons for choosing SVG.

  • They’re scalable and can be resized in a browser without loss of quality.
  • They typically result in smaller file sizes when compared to similar bitmap images.
  • They’re accessible because screen readers, search engines, etc. can read their code.
  • Text in an SVG is selectable and copyable.
  • SVG images can interact with the DOM, CSS and Javascript
  • SVG in whole or part can be animated.

Browser support for SVG basics is good as long as you don’t need to support Internet Explorer 8 or below, which is probably most, though not all of us. And if you don’t mind using a polyfill some exist for adding support to older browsers.

You can create SVG images using a vector graphics tool like Adobe Illustrator. In fact, if your current vector editing software can’t import and export .svg files, you should look into getting a better vector editing tool.

You can also open any text or code editor and write the code to create the same image you create in the software. However, other than the simplest of cases, I’d expect most scalable vector graphics you see on the web will be created working with a graphics application.

You might then wonder why I would spend weeks showing you how to work with the code behind scalable vector graphics. It’s because you probably will write and maintain some SVG code and you’ll likely edit some of the code output by graphics editors, regarldess of how you create the initial SVG.

A Simple Example

Before going any further I should probably show you an example. I’ll talk about the details in a bit, but for now here’s the code for a very simple .svg file.

1
2
3
4
5
6
<svg width="300" height="200"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink">

    <rect width="100%" height="100%" fill="green" />
</svg>

Copy the code and save it as example.svg or whatever name you prefer. Then open your .svg file directly in a browser. It’s not particularly exciting, but you should see the green rectangle below in the top left corner of your browser.

A green rectangle created as an .svg file
A green rectangle created using SVG

Let’s take a closer look at the code. The root element is <svg> and it contains a few attributes to set a width, height, and some xml looking code. Inside is a <rect> element with some attribues, which creates the green rectangle.

For now just consider the xmlns parts. It looks similar to how we were creating XHTML files not too long ago. It binds your SVG to a specific namespace so there are no collisions between similarly named elements. It isn’t necessary unless your page needs to run through an XML parser.

You’ll find variations of the above depending on who wrote the code. For example the file above would still work without the xmlns and xlink stuff. You could also rewrite the code above as the code below.

1
2
3
4
5
6
7
<svg version="1.1"
      baseProfile="full"
      width="300" height="200"
      xmlns="http://www.w3.org/2000/svg">

  <rect width="100%" height="100%" fill="green" />
</svg>

Mozilla recommends not using the doctype declaration as it might cause problems in validation. Specifying the version of SVG and setting the baseProfile is their preferred option.

You generally won’t load .svg files directly in the browser. More likely you’ll want to include your SVG in an HTML web page. Let’s see we how we can do that.

How to Display SVG Inside HTML

Whether you prefer to create SVG in a vector editing tool or by writing the code yourself, there are a few ways to display your SVG in an HTML page. You can:

  • Include SVG as an image
  • Include SVG in an iframe
  • Include SVG as an object
  • Include SVG as a data URI
  • Include SVG inline

Include SVG as an Image

This is probably the simplest way to include SVG in HTML. You create an image in your vector tool of choice (mine is currently iDraw), export the image as an .svg file and then add it inside an ordinary image tag.

1
<img src="example.svg" alt="My SVG example">

You do have to make sure your server supports .svg. It probably does, but it’s worth checking. To add support in Apache you’d add something like the following to your .htaccess file

1
2
AddType image/svg+xml svg svgz
AddEncoding gzip svgz

To be honest you could stop here and happily work with SVG the rest of your career. Think about that. As complicated as SVG might seem, you can create SVG files in your vector editor of choice and include them as you would any other image. Of course, you’d miss out on a lot of things SVG can do if you do stop here.

Instead of adding your SVG image directly inside an HTML image tag, you can add the .svg file as a background-image in your css.

1
2
3
4
.my-image {
 background: url("example.png"); /* fallback */
 background-image: url("example.svg");
}

Note the use of a fallback image (the .png), just in case.

Pretty simple, right? You’re just loading an image the same as you always have, except the file extension is .svg instead of .jpg, .png. or .gif.

There is a downside. When including SVG as an image either in your HTML or your CSS you have no way to further control the SVG through CSS. In some cases that will be fine, like when you want the SVG to be a static image. Other times you’ll want more control.

Include SVG in an Object or iframe

Similar to including SVG as an image, you can include it as an object as below.

1
2
3
<object type="image/svg+xml" data="example.svg" class="example">  
My Example SVG <!-- fallback -->
 </object>

You hook into the file via the data attribute and anything you want to display as fallback appears inside the opening and closing tags. Notice that I added a class to the object, which we can style with CSS.

1
2
3
4
5
.example {
 display: block;
 margin: 5em auto;
 border-radius: 10px;
}

Instead of an object you might embed your .svg file in an iframe, which should lead to the same result of a green rounded rectangle.

1
<iframe src="example.svg" class="example"></iframe>

Again quite simple. You can control the SVG with CSS in an iframe just as you could when embedding it in an object. I added the same .example class here and the same CSS will work as it did for the <object> code.

Include SVG as a Data URI

You can also turn your SVG into a data URI and include it as data. You can make the conversion using online or offline tools (here’s a nice drag and drop tool) and then add your data URI inside an image or object tag or inside your CSS.

1
<img src="data:image/svg+xml;base64,[data]>
1
background: url(data:image/svg+xml;base64,[data]);
1
2
3
<object type="image/svg+xml" data="data:image/svg+xml;base64,[data]>
 fallback content here
</object>

Wherever you see [data] in the code above, you’d include the actual data returned from your conversion tool of choice. Here’s how it looks when I converted example.svg.

1
2
3
<object type="image/svg+xml" data="data:image/svg+xml;base64,PCEtLQo8c3ZnIHZlcnNpb249IjEuMSIKICAgICBiYXNlUHJvZmlsZT0iZnVsbCIKICAgICB3aWR0aD0iMzAwIiBoZWlnaHQ9IjIwMCIKICAgICB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgoKICA8cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSJncmVlbiIgLz4KPC9zdmc+Ci0tPgoKPHN2ZyB3aWR0aD0iMzAwIiBoZWlnaHQ9IjIwMCIgIGNsYXNzPSJleGFtcGxlIgoJeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgoJeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPgogCgk8cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSJncmVlbiIgLz4KPC9zdmc+Cg==">
  fallback content here
</object>

Add the long string of code above inside an HTML document and you’ll see a familiar green rectangle.

Include SVG Inline

You don’t have to work with your SVG in a separate file as we have to this point. You can include SVG inline inside your html.

1
2
3
4
5
6
7
8
9
10
<body>
  <svg version="1.1"
     baseProfile="full"
     width="300" height="200"
     xmlns="http://www.w3.org/2000/svg"
     class="example">

     <rect width="100%" height="100%" fill="green" />
  </svg>
</body>

Even simpler you could write the above as:

1
2
3
4
5
<body>
  <svg width="300" height="200" class="example">
    <rect width="100%" height="100%" fill="green" />
  </svg>
</body>

Since your code will be inside HTML it won’t go through an XML parser and won’t need all the xml information. Below is some inline SVG to display a green rectangle.

Inline SVG can work well for something simple, but like most things we code, the more complex it gets, the better it is to modularize and move it into its own file.

Embedding Images Inside SVG

Instead of embedding an .svg file inside an image tag, you can do the reverse and include a bitmap image inside your SVG code.

1
2
3
4
5
6
7
<svg version="1.1"
 xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink"
 width="300" height="200">

 <image width="300" height="200" xlink:href="path-to-image.png"/>
</svg>

If you’re including a bitmap image you won’t be able to style the individual parts of the image, but you can still use other SVG features like clipping, masking, and filters, all of which I’ll cover in future posts.

SVG and WordPress

Since I work with WordPress a lot, and I’m guessing many of you do as well, I wanted to know if there was anything extra necessary to include SVG in WordPress posts and pages. There is.

Add the following code to your functions.php file and you should be able to upload .svg files through the WordPress admin like you would any other image.

1
2
3
4
5
function cc_mime_types($mimes) {
 $mimes['svg'] = 'image/svg+xml';
 return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');

If you prefer not to mess with your theme’s functions.php file you can install a plugin to do the work for you. Note that WordPress will assume your SVG is 1px by 1px (or something similarly small) unless you explicitly tell it otherwise.

For some reason WordPress doesn’t want to play nice with inline SVG, but I found a fix. If you write your inline SVG all on a single line, WordPress will display it.

1
<svg width="300" height="200"><rect width="100%" height="100%" fill="green" /></svg>

Galen Gidman offered a different solution for working with inline SVG in WordPress posts and pages. His method makes it easier to maintain SVG that you reuse on different pages of your site.

Summary

Working with SVG isn’t hard. At its simplest you can create an image in a vector graphics program, export the image as an .svg file, and include it inside an image, object, or iframe in your HTML. You could also include your .svg file in your CSS file as a background-image.

If you prefer you can create the .svg file by writing out the code, though I wouldn’t expect most people to do this for anything other than the simplest of graphics. You can include SVG directl inside HTML as inline code.

There’s a lot more you can do with SVG, though. There are more shapes that rectangles and their are plenty of effects you can add to the shapes, lines, and curves you create.

Let’s pick things up here next week. I’ll continue the series by talking about the basic SVG shapes and lines you can create.

Download a free sample from my book, Design Fundamentals.

9 comments

  1. Hello, thank you so much for this post, i am thinking in implementing SVG graphics since i am trying to make a site for myself as a web designer, but to be honest i just recently got into it, i work as a content editor, so i’m not really a web designer, anyways, thanks, i want to keep learning more and get into the modern path of web design.

    (I am from Mexico, so i apologize if there are some grammar mistakes)

    Thanks!

    • Thanks Irving. I have plenty more posts coming about SVG. I have them scheduled into the first week of February. Then I’ll probably stop talking about SVG a bit and revisit the topic later in the year.

      No need to apologize for your grammar. You write clearer than many people I know who call English their native language.

  2. I would just like to a MASSIVE THANK YOU! Honestly, you have no idea how long I’ve spent trying to find a solution to this (like 3 hours!!).

    • Thanks Lenny. Did you mean the WordPress solution? I was lucky to find that shortly after searching for why I couldn’t get things working here.

      I’d rather be able to write SVG in a more readable way, but if it has to be on a single line so be it.

  3. I am just exploring SVG. I am wondering if this file extension can be used OUTSIDE of the Web. Creating scalable images would be great for my Christmas lighting applications. But if they’re only usable on the web, this great technology would not work for me. Do you know of any file extensions that would allow me to create scalable images I can use to re-size images that may work with my Christmas light matrices? .jpg and .gif and the like do not work for me.

Leave a Reply

Your email address will not be published. Required fields are marked *