【问题标题】:How to reference different SVGs inside the same SVG file in CSS background?如何在 CSS 背景中引用同一个 SVG 文件中的不同 SVG?
【发布时间】:2020-02-04 16:05:04
【问题描述】:

我正在创建一个网站,该网站的一个非常重要的要求是文件数量最少。我可以减少文件数量的一个地方是项目的 SVG 文件。目前这个项目正在使用 10 多个 SVG 文件,我希望将它们全部组合成一个 SVG sprite sheet。由于这些 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>"");
}

我也尝试将所有 &lt;symbol&gt; 标签转换为 &lt;g&gt; 标签,但随后所有图像开始相互重叠,因此变得毫无意义。

我希望有一个解决方案,我的所有 SVG 都在一个文件中,我可以在我的 CSS 背景图像中单独引用它们。

【问题讨论】:

标签: html css svg


【解决方案1】:

这是我使用 svg sprites 作为背景的示例:

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;
}
&lt;div&gt;&lt;/div&gt;

你也可以使用#blackcat

合并后的文件如下所示: (请注意style 元素,该规则svg &gt; 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>

我希望这是你需要的。

您将在本书中找到详细解释:Using SVG with CSS3 and HTML5: Vector Graphics for Web Design

【讨论】:

    猜你喜欢
    • 2015-07-01
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    相关资源
    最近更新 更多