Getting SVG Strings for Javascript or CSS Usage

Stephen Koch
2 min readMay 14, 2019

--

The original SVG

We’ve all been there. We have this SVG that we now need to use dynamically in some way and we’re not sure how to get the properly formatted string.

In our case, it’s an SVG pin/marker needed for a Google Map that we will need to have as a default and then a different one on hover.

If I’m given an SVG I usually drop it into create a new Artboard in Sketch, drag the SVG to it, and position at `0, 0` and then copy the code directly from Sketch. This way you can remove any odd `transform` attributes over which you had no control as well as see if anything needs tweaking.

Optimized SVG

Here are the steps to get you a string that you can use via JS or CSS.

Step One

Open up your SVG and copy the code (either from Sketch or directly from your code editor).

Step Two

Head on over to Jake’s tool and paste the SVG code.

Paste here!

Step Three

Copy!

Copy the generated code. Note that you can tweak your results via the options on the right.

Step Four

Head on over to @yoksel's tool he built for this very purpose and paste the newly optimized code into the upper left input (Insert your SVG) and ask yourself: “Do I need single or double quotes?”

Step Five

Copy for CSS usage or if using in Javascript you can just use the string/value inside `url()` as seen in the above screenshot.

💥💥💥

Examples

Using SVG string in Javascript
Using SVG string in SCSS

Credit

--

--