How to use #bg as background section ?

https://jsfiddle.net/42nn4b49/2/

 div { width: 4em; } section { outline: 1px dotted red; width: 8em; height: 8em; background: url(#bg); /* не работает */ } 
 <div> <svg viewBox="-4 -4 8 8" id="bg"> <circle r="4" /> </svg> </div> <section></section> 

PS: This question is in English.

  • one
    try something like background: url (../ img / name.svg); - Lieutenant Jim Dangle
  • @FrankSinatra, no, I just need it from the markup. - Qwertiy
  • there he made a crutch with a crutch, and why is my version not suitable for you? plus it is like the page element sawed - Lieutenant Jim Dangle
  • @FrankSinatra, I have svg on d3.js going on the page. And you have to send it to the background of another element. - Qwertiy
  • association: stackoverflow.com/q/39916145/4928642 - Qwertiy

1 answer 1

Well, if the option of inserting from an external svg file background: url(../img/name.svg); , the svg can be inserted inline as an example

  background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='30' height='30'><circle cx='15' cy='15' r='10' /></svg>") no-repeat; 

You only need to declare the svg struct via the xmlns attribute: xmlns='http://www.w3.org/2000/svg'

At the expense of inserting a DOM element as a background, I could be wrong, but it seems that the css specification doesn’t allow doing so yet. If you wish, you can crutch like this:

 var section = document.querySelector("section"); value = "url('data:image/svg+xml;utf8," + document.querySelector("svg").outerHTML.replace(/\r|\n/g, '') + "')"; section.style.background = value; 
 div { width: 4em; } section { outline: 1px dotted red; width: 8em; height: 8em; /* background: url(#bg); устанавливается через js */ } 
 <div> <svg viewBox="-4 -4 8 8" xmlns="http://www.w3.org/2000/svg" id="bg"> <circle r="4" /> </svg> </div> <section class="section"></section> 

Well, or even abandon this idea and absolutely position the svg and section in the same parent.

  • one
    1. So I already experimented: jsfiddle.net/42nn4b49/9 2. As for the DOM element in the background, there is -moz-element, but this is only FF. 3. I wanted my dom-element to synchronize itself with the background with some changes - I would have to do without it ... In general, thanks for the interesting option - much more interesting than on SO. - Qwertiy
  • The * -element property seems to have moved to the 4th specification. It seems to be working in chome and mozille now. It would be convenient to use it - ArtResh
  • developer.mozilla.org/ru/docs/Web/CSS/element - just like FF? - Qwertiy
  • Yes, I blunted a little, not the property in caniuse looked - ArtResh