是否可以在CSS中使用内联SVG定义?
我的意思是:
.my-class {
background-image: <svg>...</svg>;
}
是否可以在CSS中使用内联SVG定义?
我的意思是:
.my-class {
background-image: <svg>...</svg>;
}
当前回答
我的解决方案是https://yoksel.github.io/url-encoder/ 您只需插入svg并返回背景图像代码
其他回答
我在CodePen演示中也遇到了将内联SVG嵌入CSS的问题。使用SCSS的解决方案是构建一个简单的url编码函数。
字符串替换函数可以从内置的str-slice, str-index函数中创建(参见css-tricks,感谢Hugo Giraudel)。
然后,用%xxcodes替换%,<,>,",':
@function svg-inline($string){
$result: str-replace($string, "<svg", "<svg xmlns='http://www.w3.org/2000/svg'");
$result: str-replace($result, '%', '%25');
$result: str-replace($result, '"', '%22');
$result: str-replace($result, "'", '%27');
$result: str-replace($result, ' ', '%20');
$result: str-replace($result, '<', '%3C');
$result: str-replace($result, '>', '%3E');
@return "data:image/svg+xml;utf8," + $result;
}
$mySVG: svg-inline("<svg>...</svg>");
html {
height: 100vh;
background: url($mySVG) 50% no-repeat;
}
Compass中还提供了一个图像内联助手函数,但由于CodePen不支持它,因此这个解决方案可能会有用。
CodePen上的演示:http://codepen.io/terabaud/details/PZdaJo/
如果你正在使用postcss,你可以尝试postcss-inline-svg插件https://www.npmjs.com/package/postcss-inline-svg
.up {
background: svg-load('img/arrow-up.svg', fill: #000, stroke: #fff);
}
.down {
background: svg-load('img/arrow-down.svg', fill=#000, stroke=#fff);
}
我的解决方案是https://yoksel.github.io/url-encoder/ 您只需插入svg并返回背景图像代码
来自第三方来源的内联SVG(如谷歌图表)可能在SVG元素中不包含XML名称空间属性(xmlns="http://www.w3.org/2000/svg")(或者可能在SVG呈现后将其删除-浏览器检查器和浏览器控制台的jQuery命令都不显示SVG元素中的名称空间)。
当您需要为其他需要(CSS中的background-image或HTML中的img元素)重新使用这些svg片段时,请注意丢失的名称空间。如果没有名称空间,浏览器可能会拒绝显示SVG(无论编码是utf8还是base64)。
在Mac/Linux上,你可以用这个简单的bash命令轻松地将SVG文件转换为CSS背景属性的base64编码值:
echo "background: transparent url('data:image/svg+xml;base64,"$(openssl base64 < path/to/file.svg)"') no-repeat center center;"
在Mac OS X上测试。 这样还可以避免URL转义混乱。
记住,对SVG文件进行base64编码会增加其大小,请参阅css-tricks.com的博客文章。