Skip to content

Instantly share code, notes, and snippets.

@mdarens
Created March 6, 2015 21:58
Show Gist options
  • Save mdarens/35fa0b0e37fa84fb5948 to your computer and use it in GitHub Desktop.
Save mdarens/35fa0b0e37fa84fb5948 to your computer and use it in GitHub Desktop.
Colorize an SVG in Less and inline it
// adds fill attribute to all g, polygon, path and rect children of an SVG string,
// assuming you have stripped the fill attributes already
.colorize-svg(@svg: "", @cl-fill: currentColor) {
@colorized-svg: replace(@svg, '(<g\s|<polygon\s|<path\s|<rect\s)', '$1fill="@{cl-fill}" ', 'g');
}
// You don't have to base64 SVGs unless you've embedded some binary images in them
// See https://css-tricks.com/probably-dont-base64-svg/
.make-svg-data-url(@svg: "") {
@escaped-svg: escape(@svg);
@data-url-svg: url("data:image/svg+xml,@{escaped-svg}");
}
// USAGE:
.thing {
@mySvg: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><g stroke-width="3" stroke="#fff"><rect width="60" height="60" x="12" y="28" rx="10" ry="10"/><rect width="55" height="55" x="27" y="18" rx="10" ry="10"/><rect width="40" height="40" x="47" y="11" rx="5" ry="5"/></g></svg>'
.colorize-svg(@mySvg);
.make-svg-data-url(@colorized-svg);
background-image: @data-url-svg;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment