Skip to content

Instantly share code, notes, and snippets.

@kevindees
Last active May 27, 2021 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevindees/32a65bf7e64971e2c6b294e99cee2c89 to your computer and use it in GitHub Desktop.
Save kevindees/32a65bf7e64971e2c6b294e99cee2c89 to your computer and use it in GitHub Desktop.
SVG SCSS/SASS Background Image URL Encode
// Replace letters
@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;
}
// Encode symbols
@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,#{url-encode($string)}');
}
@mixin background-svg($svg){
background-image: inline-svg($svg);
}
@kevindees
Copy link
Author

usage example:

$primary-color:  'ff00ff';

$icon-url-data-brand: inline-svg("<svg xmlns='http://www.w3.org/2000/svg' width='23' height='22' viewBox='0 0 23 22'><path fill='##{$primary-color}' d='M21.348,2.768L6.797,17.319l-5.144-5.144c-0.244-0.244-0.638-0.244-0.882,0l-0.588,0.588 c-0.244,0.244-0.244,0.638,0,0.882l6.173,6.173c0.244,0.244,0.638,0.244,0.882,0l15.58-15.58c0.244-0.244,0.244-0.638,0-0.882 l-0.588-0.588C21.986,2.524,21.591,2.524,21.348,2.768L21.348,2.768z'/></svg>");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment