Don't know where to look?

You can search all my notes here

Insert SVG-background-images in SCSS inline

The following code inlines svg-code in a way that every current browser (including IE 10) will display it correctly.

Once per project

inline-svg.scss
scss
// 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;
}

// Format the SVG as a URL
@function inline-svg($string) {
    @return url('data:image/svg+xml,#{url-encode($string)}');
}

On the specific element

scss
.el {
  background-image: inline-svg('<!-- SVG Code -->');
}

Comments

Post-Meta
  • Published: July 21, 2019
  • Last modified: April 14, 2020
  • Tags: scss svg
Included files
  • inline-svg.scss
  • readme.md
Download all