csssvgbackgroundfill

how to change svg fill color when used as base-64 background image data?


I'm using SVG for a project, loaded in css like this:

background-image: url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20version%3D%221.1%22%20x%3D%220px%22%20y%3D%220px%22%20width%3D%2222px%22%20height%3D%2238px%22%20viewBox%3D%220%200%2022%2038%22%20enable-background%3D%22new%200%200%2022%2038%22%20xml%3Aspace%3D%22preserve%22%3E%3Cstyle%3E.style0%7Bfill%3A%09%23f47216%3B%7D%3C/style%3E%3Cpath%20d%3D%22M2.643%2038c-0.64%200-1.282-0.231-1.79-0.699c-1.074-0.988-1.143-2.661-0.154-3.735l13.13-14.258L0.664%204.4%20c-0.967-1.094-0.865-2.765%200.229-3.732s2.765-0.864%203.7%200.229L19.37%2017.592c0.898%201%200.9%202.545-0.035%203.542L4.588%2037.1%20C4.067%2037.7%203.4%2038%202.6%2038z%22%20class%3D%22style0%22/%3E%3C/svg%3E');

I have some hover states to highlight by changing the fill color of the arrow.

For now, I'm simply applying the same svg data with the fill portion (fill%3A%09%23f47216%3B%7D%3C where f47216 is the color) changed with the right/new color. Works pretty well. Though, I'd like to know if there's maybe some other smarter method.


Solution

  • I want to post an answer to my own question. No exactly an answer, since it doesn't imply svg as background and base64, but it's my current alternative way, much more effective if you just need mono-color icons: just use svg as css mask, and change background color. Then you can also apply transitions on mouse events. I mean something like this:

        // or -webkit prefixed
        mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" xml:space="preserve"><path d="M11.432 9.512a.636.636 0 0 1 0 .918L2.12 19.742a.636.636 0 0 1-.458.201.637.637 0 0 1-.46-.201l-1-.998C.068 18.609 0 18.459 0 18.285s.068-.329.199-.461l7.854-7.852L.199 2.118A.638.638 0 0 1 0 1.66c0-.174.068-.327.199-.46l1-.998A.634.634 0 0 1 1.66 0c.172 0 .325.068.458.201l9.314 9.311z"/></svg>');
        mask-size: auto 12px;
        mask-repeat: no-repeat;
        transition: background-color 200ms;
        background-color: #ff0000;
    

    Please see this fiddle for more code and demo:

    https://jsfiddle.net/o25beLqj/

    Also note a couple of things: