Last active
March 18, 2020 12:53
-
-
Save certainlyakey/7588b22a00a784bdb19b to your computer and use it in GitHub Desktop.
Restylable SVG SASS mixin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//this mixin will produce a CSS property (for example background-image) which value will contain an encoded SVG with preset colors and properties | |
//use http://codepen.io/yoksel/details/JDqvs/ to get URL encoded path | |
@mixin restylable-svg($encodedpath, $width, $height, $fill_color:black, $stroke_color:false, $stroke_width:1, $prop:'background-image') { | |
// $fill_color: rgba($fill_color,.99); | |
// $stroke_color: rgba($stroke_color,.99); | |
$svgdata: '%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20%20%20width%3D%22' + $width + '%22%20height%3D%22' +$height + '%22%3E%0A%20%20%3Cpath%20d%3D%22'; | |
$stroke_attr: ''; | |
@if $stroke_color != false { | |
$stroke_attr: '%20stroke%3D%22' + encodecolor($stroke_color) + '%22%20' + '%20stroke-width%3D%22' + $stroke_width + '%22%20'; | |
} | |
$svgdata: $svgdata + $encodedpath + '%22' + $stroke_attr + '%20fill%3D%22' + encodecolor($fill_color) + '%22/%3E%0A%3C/svg%3E'; | |
#{$prop}: url('data:image/svg+xml,' + $svgdata); | |
} | |
//Helper functions | |
//from http://sassmeister.com/gist/1b4f2da5527830088e4d | |
@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; | |
} | |
//requires str-replace function | |
@function encodecolor($string) { | |
@if type-of($string) == 'color' { | |
$string:inspect($string); | |
$string:str-replace($string, '#', '%23'); | |
$string:str-replace($string, '(', '%28'); | |
$string:str-replace($string, ')', '%29'); | |
$string:str-replace($string, ',', '%2C'); | |
} | |
@return $string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment