【问题标题】:currentColor inheritance for SVG urlSVG url 的 currentColor 继承
【发布时间】:2013-12-28 20:36:25
【问题描述】:

How do I have an SVG image inherit colors from the HTML document? 相同的问题,但特别适用于用作: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>

jsFiddle Demo

【问题讨论】:

    标签: css svg


    【解决方案1】:

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

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

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

    【讨论】:

    【解决方案2】:

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

    例如不要在您的 SVG 网址中使用 currentColor,而是使用基色,例如red 然后,不要更改包含元素上的color(您的包含元素是&lt;body&gt;,用于说明目的,但我在这里考虑的是&lt;a href="#" class="checkmark"&gt;),而是向元素添加一个过滤器:

    .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 */
    }
    

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

    【讨论】:

      猜你喜欢
      • 2012-04-03
      • 1970-01-01
      • 2021-07-18
      • 2021-11-12
      • 2020-01-03
      • 2014-09-09
      • 1970-01-01
      • 2015-05-16
      • 2021-08-29
      相关资源
      最近更新 更多