【问题标题】:SVG Icon to inherit text color and sizeSVG图标继承文本颜色和大小
【发布时间】:2021-07-11 00:59:48
【问题描述】:

我想要一些图标继承父元素的颜色和文本大小。我还希望它易于在代码的不同部分重用。

我尝试在 SVG 路径中使用fill="currentColor",但图标的颜色并没有变成与文本相同的颜色。图标总是变黑。 (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>

结果:

在上面的示例中,我希望第一个图标为蓝色,第二个为红色。

【问题讨论】:

    标签: css svg


    【解决方案1】:

    mask 结合background:currentColor; 可以做到,但你还必须设置一个宽度:

    .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>

    【讨论】:

      猜你喜欢
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 2018-09-27
      • 1970-01-01
      • 2014-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多