阅读所有这些答案让我想到了一个不错的方法来处理SASS (.scss)中的SVG,它可以编译CSS,用于我的样式主题,并且可以使color
正常工作。对于我的用例,我想(需要)使用content: url(..svg)
,因为我的库支持字体和现在使用content: $my-icon;
在伪元素:before
中支持SVG和字体。
首先创建一个SASS函数来处理颜色的
urlencode
(因为
content:url()
需要编码,
#
需要变成
%23
)。我从别人那里复制了这个函数
Gist。例如,这将取出
#fafafa
并返回
%23fafafa
,然后我可以在SVG的
fill
中使用它。你也可以不用它,只需记得在
fill
属性中将
#
更改为
%23
。
@function encodecolor($string) {
@if type-of($string) == 'color' {
$hex: str-slice(ie-hex-str($string), 4);
$string:unquote("#{$hex}");
}
$string: '%23' + $string;
@return $string;
}
我的库中定义了一些SASS变量用于主题样式,所以我可以使用字体和/或SVG(我添加了width
和display
,但也可能不需要)。
.sort-indicator-desc:before {
content: $icon-sort-desc;
display: inline-block;
width: $icon-sort-font-size;
font-size: $icon-sort-font-size;
}
最后,最终用户仍然可以使用类似 Font Awesome 4 的字体系列来使用它。
$icon-font-family: "FontAwesome"; // Font Awesome 4
$icon-sort-color: #0070d2;
$icon-sort-font-size: 13px;
$icon-sort-asc: "\f0d8"; // unicode value of the icon
$icon-sort-desc: "\f0d7";
// this compiles to => `content: "\f0d8";
或者使用SVG(例如Font Awesome 5)
@import './sass-utilities'; // sass helper
$icon-sort-color: #0070d2;
$icon-sort-font-size: 13px;
$icon-sort-asc: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" fill="#{encodecolor($icon-sort-color)}" viewBox="0 0 24 24" id="arrowdown"><path d="M19.1 9.7c.4-.4.4-.9 0-1.3l-6.9-6.7c-.4-.4-.9-.4-1.3 0L4 8.4c-.4.4-.4.9 0 1.3l1.3 1.2c.3.4.9.4 1.3 0l2.1-2.1c.4-.4 1-.1 1 .4v12.5c0 .5.5.9 1 .9h1.8c.5 0 .9-.5.9-.9V9.2c0-.5.7-.8 1-.4l2.2 2.1c.4.4.9.4 1.3 0l1.2-1.2z"></path></svg>');
$icon-sort-desc: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" fill="#{encodecolor($icon-sort-color)}" viewBox="0 0 24 24" id="arrowdown"><path d="M4.4 14.3c-.3.4-.3.9 0 1.3l7 6.7c.3.4.9.4 1.2 0l7-6.7c.4-.4.4-.9 0-1.3l-1.3-1.2c-.3-.4-.9-.4-1.3 0l-2.1 2.1c-.4.4-1.1.1-1.1-.4V2.3c0-.5-.4-.9-.9-.9h-1.8c-.5 0-.9.5-.9.9v12.5c0 .5-.7.8-1.1.4L7 13.1c-.4-.4-1-.4-1.3 0l-1.3 1.2z"></path></svg>');
// this compiles to => `content: url('data:image/svg+xml,<svg>...');
最终,我成功地使用SASS变量同时实现了字体和SVG,这非常棒,因为这意味着我的库(
Angular-Slickgrid)的任何用户都可以使用 Font Awesome 4 图标(字体),而其他人也可以使用 SVG(例如Font Awesome 5),而无需安装字体族(
.eof
,
.woff
等),这取决于库的大小。最终结果仍然是一个已编译的CSS文件,带有
content
以加载带有额外
fill
属性用于SVG颜色的SVG。
瞧!我得到了最好的两者 :)