Is there an equivalent of spriting for SVG images

2019-03-19 17:15发布

SVG images aren’t bitmaps, so (unless I’m missing something) you can’t do spriting like you can with other images files used on web pages (see http://www.alistapart.com/articles/sprites).

But is there an equivalent mechanism to display only part of an SVG image as a CSS background?

E.g. imaginary syntax:

div.my-special-svg-div {
    background-image: url(sprite-image.svg#one-shape-in-the-svg-file);
}

4条回答
再贱就再见
2楼-- · 2019-03-19 17:51

You can use 'traditional' CSS sprite techniques to slice up SVG images with background position, here's a quick example, though it does get a little confusing if you also start using background-size. It's probably easier if you define a size on your SVG image:

<svg version="1.1" 
     xmlns:svg="http://www.w3.org/2000/svg"
     xmlns="http://www.w3.org/2000/svg"
     width="320"
     height="240"
     viewBox="0 0 320 240">
查看更多
闹够了就滚
3楼-- · 2019-03-19 17:57
甜甜的少女心
4楼-- · 2019-03-19 18:04

SVG isn't even technically supported by W3C standards. It won't even work in IE without a plugin. Maybe you'll find some obscure Mozilla plugin that lets you do that but as far as I know your code won't validate.

查看更多
时光不老,我们不散
5楼-- · 2019-03-19 18:10

One approach I’ve tried that isn’t spriting, but achieves similar aims, is to include url-encoded SVG images directly in the CSS file, using data URIs.

E.g.

background-image: url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%0A%20%20%3Crect%20fill%3D%22%23CCD%22%20%20width%3D%22100%25%22%20height%3D%22100%25%22%2F%3E%0A%20%20%3Crect%20fill%3D%22%23039%22%20width%3D%22100%25%22%20height%3D%22100%25%22%20rx%3D%221em%22%2F%3E%0A%3C%2Fsvg%3E);

(See http://intertwingly.net/blog/2008/09/07/SVG-via-CSS)

So, all your SVG images end up in the CSS file. Gzipping should squish multiple SVG files in one CSS file quite nicely.

As far as I can tell, the CSS above works in Opera 9.5+, IE 9 beta, Safari 5, and Chrome 6. Doesn’t seem to work in Firefox as of 3.6, or earlier versions of the other browsers.

查看更多
登录 后发表回答