Change color of data url embedded SVG image

2019-01-20 15:11发布

I have an SVG background image embedded in a CSS file as a data url:

.what { background: url('data: image/svg+xml; utf8, <svg> ... </svg') }

I want another element to have the same background image, only in a different color, but I don't want to repeat the whole SVG code.

<div class="what one">...</div>
<div class="what two">...</div>

So how do I change the color of a background SVG image?

No Javascript, please.


None of the other related questions answered this, because the solutions given there rely on serving two different files, which I want to avoid because I want to minimize file size for mobile users.

标签: css svg
3条回答
贼婆χ
2楼-- · 2019-01-20 15:49

Check out this webpage: https://css-tricks.com/using-svg/ Part way down the page is a header called "Now you can control with CSS!" They appear to be changing the color of the image inline with statements such as

.kiwi {
    fill: #94d31b; 
}
查看更多
三岁会撩人
3楼-- · 2019-01-20 15:55

Apparently, as Noah Blon explains, it is possible to style the color of an SVG background image using CCS filters.

An example he gives on his site is:

.icon-blue {
    -webkit-filter: hue-rotate(220deg) saturate(5);
    filter: hue-rotate(220deg) saturate(5);
}

Please visit his site for more information and two other solutions that do not involve changing the color but SVG background sprites and creating an "inverted" SVG that covers the background and is transparent where the background color shines through to create a colored form.

Unfortunately, IE does not support filters.

查看更多
在下西门庆
4楼-- · 2019-01-20 16:06

You can't restyle the contents of a background image with CSS. It doesn't matter if it's an external SVG, or one applied as a Data URI.

查看更多
登录 后发表回答