Skip to content

Instantly share code, notes, and snippets.

@gexiangdong
Last active July 2, 2023 12:21
Show Gist options
  • Save gexiangdong/372d94b1dc103cb170fbad282620bd44 to your computer and use it in GitHub Desktop.
Save gexiangdong/372d94b1dc103cb170fbad282620bd44 to your computer and use it in GitHub Desktop.
CSS中用SVG图片做背景图

用CSS把SVG图片显示为背景图,可分为2种写法:

  1. 单独的.svg文件,css里用 background-image: url('xx.svg'); 去调用
  2. 使用url的data属性,把svg文件合并到css中

第2种写法直接把svg的xml内容拷贝到css中,有些浏览器会识别不出来,这是由于写法不规范造成的。 规范的写法把svg内容放到css内时需要encode,有两种encode方式: base64 和 URLEncode

base64

做base64的编码后,需要 background-image: url('data:image/svg+xml;base64,这里放base64后的svg')

urlencode

urlencode可以直接放 background-image: url('data:image/svg+xml;charset=utf-8,这里放urlencode后的svg)

但需要注意URLEncode有两种可能:

空格变加号,这是在 content type 是 'application/x-www-form-urlencoded'时,也就是提交表单时,POST DATA的URLEncoding方式。

空格变%20,这是标准的URL的encode, 在css中使用svg需要用这种encode方法。

如果你找到的工具编码出来空格是加号,可以把+都替换成%20即可。

Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<!DOCTYPE html>
<html>
<head>
<title>svg background</title>
<style type="text/css">
div {margin: 50px; border: 1px solid #CDCDCD; padding:5px; height:150px; width:300px; background-repeat: no-repeat; background-position: center center; float:left;}
.bg1{background-image: url('bg.svg');}
.bg2{background-image: url('data:image/svg+xml;charset=utf-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20x%3D%220%22%20y%3D%220%22%20width%3D%22100%22%20height%3D%22100%22%20viewBox%3D%220%2C%200%2C%20100%2C%20100%22%20fill%3D%22%23ECECEC%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%2F%3E%3C%2Fsvg%3E');}
.bg3{background-image: url('data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjAiIHk9IjAiIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIiB2aWV3Qm94PSIwLCAwLCAxMDAsIDEwMCIgZmlsbD0iI0VDRUNFQyI+PGNpcmNsZSBjeD0iNTAiIGN5PSI1MCIgcj0iNTAiLz48L3N2Zz4=');}
.bg4{background-image: url('data:image/svg+xml;charset=utf-8,<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0" y="0" width="100" height="100" viewBox="0, 0, 100, 100" fill="#ECECEC"><circle cx="50" cy="50" r="50"/></svg>');}
</style>
</head>
<body>
<div class="bg1">使用独立的svg文件</div>
<div class="bg2">urlencode, urlencode编码,注意空格需要编码成%20,空格转义成加号的方式无效</div>
<div class="bg3">base64,用base64编码后的</div>
<div class="bg4">直接写,这是不规范的写法,可能有部分浏览器会生效,能看到背景图</div>
</body>
</html>
@xxwwp
Copy link

xxwwp commented Jan 4, 2023

urlencode 非常有效!感谢

@15526441465
Copy link

非常有效!感谢

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment