我正在创建一个网站,该网站的一个非常重要的要求是文件数量最少。我可以减少文件数量的一个地方是项目的SVG文件。目前,该项目正在使用10多个SVG文件,我希望将它们全部合并到一个SVG Sprite表中。由于这些SVG文件在CSS中被用作背景图像,因此:
.class-name {
background-image: url(/path/to/file.svg)
}
我现在有一个svg文件,其中以前的SVG文件中的每个文件都是一个符号,因此svg文件如下所示:
<svg>
<symbol id="id1">....</svg>
<symbol id="id2">....</svg>
<symbol id="id3">....</svg>
...
</svg>
我希望在我的CSS中使用这些符号,如下所示:
.class-name {
background-image: url(/path/to/combined-file.svg#id1)
}
如何在背景图片中使用SVG符号。
我已经尝试了以下方法:
.class-name {
background-image: url(/path/to/combined-file.svg#id1)
}
并且
.class-name {
background-image: url("data:image/svg+xml;base64,<svg><use xlink:href="path/to/combined-svg#id1/></svg>"");
}
我也尝试过将所有<symbol>
标签转换为标签,<g>
但随后所有图像开始相互重叠,因此变得毫无意义。
我希望所有我的SVG都在一个文件中的解决方案,并且可以在CSS背景图像中分别引用它们。
这是我使用svg精灵作为背景的示例:
div{width:300px;height:300px; border:1px solid;
background-image:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/cat.svg#redcat);
background-size:200px;
background-repeat: no-repeat;
background-position: center;
}
<div></div>
您也可以使用#blackcat
合并后的文件如下所示:(请注意style
该规则svg > svg:not(:target) {display: none;}
将隐藏所有嵌套的svg元素的元素,除非它们是目标)
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100px" height="100px" viewBox="0 0 225 225">
<style type="text/css">
<![CDATA[
/* this is hiding all the nested svg elements unless they are the target*/
svg > svg:not(:target) {
display: none;
}
]]>
</style>
<desc>
<g id="cat">
<path id="body" fill-rule="evenodd" clip-rule="evenodd" d="M121.506,108.953.....108.953z"/>
<path id="head" fill-rule="evenodd" clip-rule="evenodd" d="M129.747,18.651......81.453z"/>
</g>
</desc>
<svg version="1.1" id="blackcat" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 225 225">
<use xlink:href ="#cat" fill="black" />
</svg>
<svg version="1.1" id="redcat" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 225 225">
<use xlink:href ="#cat" fill="red" />
</svg>
</svg>
我希望这是您所需要的。
您将在本书中详细解释以下内容:将SVG与CSS3和HTML5一起使用:Web设计中的矢量图形
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句