SVG Icon to inherit text color and size

Viewed 722

I would like to have some icons that inherit the color and text size of the parent element. I would also like it to be easy to reuse in different parts of the code.

I tried to use fill="currentColor" in the SVG path, but the color of the icon does not become the same color as the text. The icon always become black. (jsfiddle)

.my-icon-inherit-font-size-and-color {
  content: url('data:image/svg+xml;utf8, <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 16 16"> <path d="M2 15.5a.5.5 0 0 0 .74.439L8 13.069l5.26 2.87A.5.5 0 0 0 14 15.5V2a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v13.5zM8 4.41c1.387-1.425 4.854 1.07 0 4.277C3.146 5.48 6.613 2.986 8 4.412z"/></svg>');
  height: 0.7em;
}
<p>
  <a href="#" style="font-size: 28px; color: blue">
    <i class="my-icon-inherit-font-size-and-color"></i> Some text
  </a>
</p>

<p>
  <a href="#" style="font-size: 38px; color: red">
    <i class="my-icon-inherit-font-size-and-color"></i> Some text
  </a>
</p>

Result:

result

In the example above, I would like the first icon to be blue and the second red.

1 Answers

mask combined with background:currentColor; can do it but you have to also set a width:

.my-icon-inherit-font-size-and-color {
  display:inline-block;
  height: 0.7em;
  width:0.5em;
  background:currentColor;
  -webkit-mask:url('data:image/svg+xml;utf8, <svg xmlns="http://www.w3.org/2000/svg"  viewBox="0 0 16 16"> <path d="M2 15.5a.5.5 0 0 0 .74.439L8 13.069l5.26 2.87A.5.5 0 0 0 14 15.5V2a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v13.5zM8 4.41c1.387-1.425 4.854 1.07 0 4.277C3.146 5.48 6.613 2.986 8 4.412z"/></svg>') center/cover;
}
<p>
  <a href="#" style="font-size: 28px; color: blue">
    <i class="my-icon-inherit-font-size-and-color"></i> Some text
  </a>
</p>      
    
<p>
  <a href="#" style="font-size: 38px; color: red">
    <i class="my-icon-inherit-font-size-and-color"></i> Some text
  </a>
</p>

Related