Tuesday, 22 April 2014

Filled Under:

A Super-Simple Way To Use SVG

23:18:00


Instead, I thought I’d share a super simple way to use SVG with you, quite possibly the easiest way. Everyone’s talking SVG these days and it’s something I’ve been advocating for quite a while on this site.

With all its possibilities, there’s so much that can be done with SVG. However sometimes, you might want to set the background: property of an element via CSS, without using an all important HTTP request. We can use SVG’s as a data-URI in this situation. Here’s how.

Download your favourite SVG.

Download whatever SVG you like. It could be an icon, an illustration or whatever. Here I’m using the CodePen logo found here.
code-pen-logo-example

Create an HTML element.

Create an HTML element like a div or a span.
HTML
<div class="svg"></div>

Open the SVG file in a text-editor.

Copy the SVG code and minify it. You could use this free online minifier here.
svg-code-example

Set the background as a data-URI

Set the background property to a data-URI with the SVG code inserted like this. Then set the background-size to contain.
CSS
.svg {
background:url('data:image/svg+xml;utf8,/*SVG Code*/);
background-size: contain;
height: 250px;
width: 250px;
}
That’s it. Note that it will only work un-encoded on -webkit browsers. For full browser support, encode the SVG data with this URL ENCODER.
There are quite a few disadvantages in using both data-URI’s and SVG this way. I certainly wouldn’t use this technique for an entire project or anything. However there are other times where it could come in handy (like quickly styling an input button on a form for example). Anyways it’s nice to know you can do it this way (on webkit) without having to encode the SVG markup.
See the Pen fHmbt by Abhishek (@abhibagul) on CodePen.

0 comments:

Post a Comment