【问题标题】:How to Change SVG color in SCSS using currentColor如何使用 currentColor 在 SCSS 中更改 SVG 颜色
【发布时间】:2020-06-10 21:17:27
【问题描述】:

如何使用 currentColor 填充 svg?我想像这样在 svg 背景中使用当前元素颜色:

.icon {
 color:bleu;
&::after {
    content: '';
    display: inline-block;
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center center;
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 19 15" fill="currentColor"> <polygon points="9 14 1 14 1 1 9 1 9 4.5 10 4.5 10 0 0 0 0 15 10 15 10 10.5 9 10.5 9 14"></polygon> <polygon points="14.708 3.146 14.011 3.854 17.113 7 4.5 7 4.5 8 17.113 8 14.011 11.146 14.708 11.854 19 7.5 14.708 3.146"></polygon> </svg>');
    width: 19px;
    height: 15px;
    margin-left: 14px;
    position: absolute; // hide underline on hover
    top: 2px;

}

&:focus {
    &::after {
        position: inherit; // show border on focus and save the top position
    }
}

&:hover {
    color:red;
    &::after {
        background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 19 15" fill="currentColor"> <polygon points="9 14 1 14 1 1 9 1 9 4.5 10 4.5 10 0 0 0 0 15 10 15 10 10.5 9 10.5 9 14"></polygon> <polygon points="14.708 3.146 14.011 3.854 17.113 7 4.5 7 4.5 8 17.113 8 14.011 11.146 14.708 11.854 19 7.5 14.708 3.146"></polygon> </svg>');
    }
}
}

有什么想法吗?

【问题讨论】:

  • 你可以使用javascript来设置背景图片并使用css vars而不是currentColor

标签: css svg sass


【解决方案1】:

使用url 技术添加这样的背景图像会为 svg 创建一个新的上下文,从而有效地使currentColor 成为默认浏览器颜色。所以你不能这样做。

但是,您可以执行以下操作:

  1. 将 SVG 填充颜色设置为蓝色 fill="blue"
  2. 在悬停时,使用filter: hue-rotate() 为背景着色

在你的情况下

.icon {
  &::after {
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 19 15" fill="blue"> <polygon points="..."></polygon> </svg>');
  }

  &:hover {
    color: red;
    &::after {
      filter: hue-rotate(120deg);
    }
  }
}

或者只是

  &:hover {
    filter: hue-rotate(120deg);
  }

这会将过滤器应用于图标和常规文本。

【讨论】:

    猜你喜欢
    • 2019-06-22
    • 2021-03-15
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 2021-11-25
    • 2017-09-11
    相关资源
    最近更新 更多