Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Inline SVG function [SASS]
// set svg d path used as fallback (star)
$svg-d-path: 'm25,1l6,17l18,0l-14,11l5,17l-15,-10l-15,10l5,-17l-14,-11l18,0l6,-17z' !default;
// functions to urlencode the svg string
@function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
}
@function url-encode($string) {
$map: (
"%": "%25",
"<": "%3C",
">": "%3E",
" ": "%20",
"!": "%21",
"*": "%2A",
"'": "%27",
'"': "%22",
"(": "%28",
")": "%29",
";": "%3B",
":": "%3A",
"@": "%40",
"&": "%26",
"=": "%3D",
"+": "%2B",
"$": "%24",
",": "%2C",
"/": "%2F",
"?": "%3F",
"#": "%23",
"[": "%5B",
"]": "%5D"
);
$new: $string;
@each $search, $replace in $map {
$new: str-replace($new, $search, $replace);
}
@return $new;
}
@function inline-svg($string) {
@return url('data:image/svg+xml;charset=US-ASCII,#{url-encode($string)}');
}
@JacobDB

This comment has been minimized.

Copy link

JacobDB commented Jan 26, 2017

Pretty neat, but I changed a couple of small things so it works better with UTF-8 encoding :) https://gist.github.com/JacobDB/0ffffaf8e772c12acf7102edb8a302be

@ahmedam55

This comment has been minimized.

Copy link

ahmedam55 commented Jul 10, 2018

I tried encoding this svg: <svg width='20' height='20' xmlns='http://www.w3.org/2000/svg'><g transform='translate%28-13 -12%29' fill='none' fill-rule='evenodd'><path d='M0 0h45v45H0z'/><circle fill='%239B9B9B' cx='23' cy='22' r='10'/><path fill='%23FFF' fill-rule='nonzero' d='M27.3967 17l1.4296 1.5388-7.852 8.4516L17 22.7126l1.4296-1.5388 2.5447 2.739z'/></g></svg> and it took 3 seconds only for this scss code:

.foo {
  background-image: 
  url("data:image/svg+xml,#{url-encode("<svg width='20' height='20' xmlns='http://www.w3.org/2000/svg'><g transform='translate%28-13 -12%29' fill='none' fill-rule='evenodd'><path d='M0 0h45v45H0z'/><circle fill='%239B9B9B' cx='23' cy='22' r='10'/><path fill='%23FFF' fill-rule='nonzero' d='M27.3967 17l1.4296 1.5388-7.852 8.4516L17 22.7126l1.4296-1.5388 2.5447 2.739z'/></g></svg>")}");
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.