Embedding a referential SVG image into HTML file

2019-07-12 08:20发布

问题:

I have a project where I want to put simple graphic backgrounds into table cells. background-image and a small svg file works great!

But I would really like to keep the source all in one file. That is, I would like to be able to define the image in the HEAD, and refer to it in the inline STYLE css.

I have tried various combinations of ID attributes in the svg and hash references in a css url() function, but no success. This would seem to be a desirable thing to do, but looking around, I haven't seen a hint of an idea. Which tells me either it cannot be done, or it is done some other way...

Suggestions?

回答1:

You can save your svg file elsewhere and put that up in an iframe.

<iframe src="index.svg" width="100%" height="100%" />

There might be other methods too..

Best tuts for svg is found MDN.



回答2:

Actually after asking the question and thinking about it, I realized I had read the answer already. You need to use a a data url to create an in-line svg graphic. This you can give to the background-image property of a css class, as thus:

{background-image:url( "data:image/svg+xml;utf8,\ ...\ ");}

The encoding utf8 will allow you to type in the code directly, escaping the new lines with backslashes and avoiding double quotes (as far as I know;-). Now you just set the CLASS of the TD and it works great!

Now all I have to do is figure out how to align the background on the bottom rather than the top...



回答3:

This code might also work:

 <svg>
    <use xlink:href="..." /> 
 </svg>