Sass SVG inline background interpolation tricks
Creating a dynamic SVG inline background with Sass can bring many surprises. Let me share these tricks.
Lessons learned
Today I created an inline SVG background generated by Sass and I learned few things:
- Sass can interpolate also with
#{}
syntax - Sass has some builtin string functions like
str-slice
- SVG inline colors in hex format must be encoded, since it is actually a data URI, so
fill="magenta"
works, butfill="#ff00ff"
will not, will work if encoded (i.e.fill="%23ff00ff"
); credits to this Codepen’s author.
Show me the code
Follows a basic example code implementing a dynamic SVG inline background with Sass.
$half-size: 20;
$size: $half-size * 2;
$sizePx: $half-size * 2px;
$color: #ff00ff;
.foo {
background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" height="#{$sizePx}" width="#{$sizePx}" viewBox="0 0 #{$size} #{$size}"><circle cx="#{$half-size}" cy="#{$half-size}" r="#{$half-size}" fill="%23#{str-slice(#{$color}, 2)}"></circle></svg>');
}