阅读所有这些答案后,我想出了一种在 SASS (.scss) 中处理 SVG 的好方法,它编译 CSS,用于我的样式主题,并且还让 color 工作。对于我的用例,我想(需要)使用content: url(..svg),因为我的库支持字体,现在通过在伪content: $my-icon; 中使用content: $my-icon; 支持SVG,这是唯一同时适用于字体/SVG 的东西。
首先是创建一个SASS函数来处理颜色的urlencode(因为content: url()需要编码,#需要变成%23)。作为参考,我从别人Gist那里复制了这个函数。例如,这将采用#fafafa 并返回%23fafafa,然后我可以在SVG 的fill 中使用它。您也可以不使用它,只需记住将fill 属性中的# 更改为%23。
/* sass-utilities.scss */
@function encodecolor($string) {
@if type-of($string) == 'color' {
$hex: str-slice(ie-hex-str($string), 4);
$string:unquote("#{$hex}");
}
$string: '%23' + $string;
@return $string;
}
我的 lib 有一些为主题样式定义的 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)一起使用
/* with a Font */
$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
/* with SVG */
$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>...');
所以最后,我让 Font 和 SVG 都与 SASS 变量一起工作,这很棒,因为这意味着我的 lib (Angular-Slickgrid) 的任何用户仍然可以使用 Font Awesome 4 图标(字体)而其他人可以也可以使用 SVG(如 Font Awesome 5),而无需安装字体家族(.eof,.woff,...),这取决于 lib。最终结果仍然是带有 content 的编译 CSS 文件,用于加载带有额外 fill SVG 颜色属性的 SVG。
然后瞧!我两全其美:)