Warm tip: This article is reproduced from serverfault.com, please click

Setting a css background image to an inline SVG symbol?

发布于 2015-02-12 12:16:16

I know external svg files can be linked to background images:

background-image: url(Icon.svg);

and symbols id's can be targeted from an external svg file:

background-image: url(Icons.svg#Icon-Menu);

but how can I set a background image to an inline svg symbol? (As below)

My svg is at the top of my web page body and not in an external file.

I want .test background image to be the #Icon-Menu symbol.

.test{
  background:#ddd url('../#Icon-Menu');
  height:100px;
  width:100px;
  display:block;
}
<div style="height: 0; width: 0; position: absolute; visibility: hidden;">
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <symbol id="Icon-Menu" viewBox="0 0 512 512">
      <title>Menu</title>
      <path d="M93.417,5.333H6.583c-1.654,0-3,1.346-3,3v13.334c0,1.654,1.346,3,3,3h86.833c1.654,0,3-1.346,3-3V8.333	C96.417,6.679,95.071,5.333,93.417,5.333z" />
      <path d="M93.417,40.333H6.583c-1.654,0-3,1.346-3,3v13.334c0,1.654,1.346,3,3,3h86.833c1.654,0,3-1.346,3-3V43.333	C96.417,41.679,95.071,40.333,93.417,40.333z" />
      <path d="M93.417,75.333H6.583c-1.654,0-3,1.346-3,3v13.334c0,1.654,1.346,3,3,3h86.833c1.654,0,3-1.346,3-3V78.333	C96.417,76.679,95.071,75.333,93.417,75.333z" />
    </symbol>
  </svg>
</div>

<div class="test"></div>
Questioner
DreamTeK
Viewed
0
Robert Longson 2017-09-22 04:04:36

An image must be a complete file.

From the SVG specification...

The ‘image’ element indicates that the contents of a complete file are to be rendered...

The same is true for background-image etc.