Embedding a referential SVG image into HTML file

2019-07-12 08:12发布

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?

3条回答
Viruses.
2楼-- · 2019-07-12 08:51

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楼-- · 2019-07-12 08:51

This code might also work:

 <svg>
    <use xlink:href="..." /> 
 </svg>
查看更多
时光不老,我们不散
4楼-- · 2019-07-12 09:03

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.

查看更多
登录 后发表回答