Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a css background image to an inline SVG symbol?

Tags:

html

css

icons

svg

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>
like image 979
DreamTeK Avatar asked Feb 12 '15 12:02

DreamTeK


3 Answers

@Robert Longson

thats right. But you can do it this way. But symbol is not the way it will work. Unfortunatly you have to use "g" or something like that to reference.

body {
  background: url(http://www.broken-links.com/tests/images/faces.svg#devil-view);
}

http://codepen.io/Type-Style/pen/ByvKJq

It will not work if the svg is in the Markup.

like image 142
Type-Style Avatar answered Oct 16 '22 22:10

Type-Style


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.

like image 4
Robert Longson Avatar answered Oct 17 '22 00:10

Robert Longson


(1) one possible way with inline SVG would be to use symbols and DIV absolute layering:

<a class="preview-modal__device-icon-link" ng-click="setPreviewWidth('phone')">
   <svg class="preview-modal__device-icon"><use xlink:href="#icon-phone">
   </use></svg>
</a>

(2) Second solution would be to use a Data URI: there is a good info here: https://css-tricks.com/using-svg/ using this tool: Mobilefish.com online conversion tool

CSS:

.logo {
  background: url("data:image/svg+xml;base64,[data]");
}

HTML:

<img src="data:image/svg+xml;base64,[data]">
like image 2
Stxle Avatar answered Oct 16 '22 23:10

Stxle