SVG url 的 currentColor 继承

Ada*_*dam 5 css svg

与如何让 SVG 图像从 HTML 文档继承颜色相同的问题?,但特别是当应用于用作:before伪元素内容的 svg 图像时。

(期望的行为是两个复选标记都从主体继承红色。目前只有内联 SVG 这样做。)

<style type='text/css'>
    body {
        color: red;
    }

    .checkmark {
        height: 2em;
        width: 2em;
    }

    .checkmark:before {
        content: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100%' height='100%' viewBox='-0.5 0 20 15'><rect fill='currentColor' stroke='none' transform='rotate(45 4.0033 8.87436)' height='5' width='6.32304' y='6.37436' x='0.84178'></rect><rect fill='currentColor' stroke='none' transform='rotate(45 11.1776 7.7066)' width='5' height='16.79756' y='-0.69218' x='8.67764'></rect></svg>");
    }
</style>

<!-- Renders red -->
<svg xmlns='http://www.w3.org/2000/svg' width='2em' height='2em' viewBox='-0.5 0 20 15'><rect fill='currentColor' stroke='none' transform='rotate(45 4.0033 8.87436)' height='5' width='6.32304' y='6.37436' x='0.84178'></rect><rect fill='currentColor' stroke='none' transform='rotate(45 11.1776 7.7066)' width='5' height='16.79756' y='-0.69218' x='8.67764'></rect></svg>

<!-- Renders #000 -->
<div class="checkmark"></div>
Run Code Online (Sandbox Code Playgroud)

jsFiddle 演示

Eri*_*röm 7

content: url(...)使 url 部分成为图像,换句话说,svg 成为它自己的单独文档。样式不适用于文档,因此color在这种情况下不可能影响 svg。

当 svg 内联时,它是文档的 OTOH 部分,因此可以对其应用样式。

您可以制作(或动态生成)复选标记 svg 的多个版本并调整样式规则,以便选择适当的“预着色”。


Eog*_*anM 5

对于图标都是相同颜色的某些用例,您可以filter在元素上使用 css而不是更改它的颜色。

例如,不要用currentColor你的SVG网址,而是使用基色如red 然后,而不是改变的color含有元素(包含你的元素是<body>用于说明目的,但我的思维<a href="#" class="checkmark">在这里),一个过滤器添加到元素:

.checkmark {
    color: red;  /* matches fill in the SVG */
}

.checkmark::before {
    content: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100%' height='100%' viewBox='-0.5 0 20 15'><rect fill='red' stroke='none' transform='rotate(45 4.0033 8.87436)' height='5' width='6.32304' y='6.37436' x='0.84178'></rect><rect fill='red' stroke='none' transform='rotate(45 11.1776 7.7066)' width='5' height='16.79756' y='-0.69218' x='8.67764'></rect></svg>");
}

.checkmark::before:hover {
    filter: hue-rotate(120deg);  /* changes both text and tick from red to green */
}
Run Code Online (Sandbox Code Playgroud)

您必须使用过滤器来获得正确的颜色转换,例如您还可以更改亮度或使其成为灰度:https : //css-tricks.com/almanac/properties/f/filter/