Search code examples
csssvg

currentColor inheritance for SVG url


Same question as How do I have an SVG image inherit colors from the HTML document?, but specifically when applied to an svg image used as content on a :before pseudo-element.

(Desired behavior is that both checkmarks inherit the red color from the body. Currently only the inline SVG does.)

<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


Solution

  • Little update. Browsers now have mask-image.

    So you can now do this:

    &::after {
      display: inline-block;
      width: 24px;
      height: 24px;
      background-color: currentColor;
      content: '';
      mask-image: url(${imgdatauri});
      mask-type: alpha;
    }