Reuse SVG sprite. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Reuse SVG sprite.

I have an SVG sprite that works well if I include it in my HTML template. So I decided to separate it to its own file, sprite.svg, so that I can cache it. I am using <use xlink:href....> tags to fetch the images. But I found out my CSS styles no longer work on it. I think it is because it is not of the same DOM tree. Has anyone faced a similar problem? What can I do?

6th Jul 2020, 6:07 PM
Ore
Ore - avatar
8 Answers
+ 1
Ore Refer to https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use The document highlighted that "Since the cloned nodes are not exposed, care must be taken when using CSS to style a use element and its cloned descendants. CSS properties are not guaranteed to be inherited by the cloned DOM unless you explicitly request them using CSS inheritance."
7th Jul 2020, 2:13 AM
Calviղ
Calviղ - avatar
+ 1
My colleague had the same case, it turned out that there was an error in the sprite that he had assembled manually and automatic assembly helped him. This is one of the options.
6th Jul 2020, 8:21 PM
Anna/Аня
Anna/Аня - avatar
0
Try collecting sprite through Gulp
6th Jul 2020, 6:47 PM
Anna/Аня
Anna/Аня - avatar
0
Anna/Аня It is not a Node project and I don't think Node is installed in the target machine. I was hoping that there is some sort of hack that makes CSS accessible cross-DOM
6th Jul 2020, 8:16 PM
Ore
Ore - avatar
0
Anna/Аня Thanks but I am very sure there is no error in my file because it worked perfectly when I insert it in my HTML. It also works in the external file but my styles no longer affect the icons. If needed, I can upload the necessary code to Sololearn to give a better picture.
6th Jul 2020, 8:29 PM
Ore
Ore - avatar
0
Calviղ Of course, I have checked the docs before and it clearly says ``` There is currently no defined way to set a cross-origin policy for use elements. ``` If I don't find an hack around this, I might have to style the icons within the SVG file itself although that means I have a less reusable sprite. I think this one of those situations where I have to forsake reusability for performance.
7th Jul 2020, 6:13 AM
Ore
Ore - avatar
0
Ore there's not the one i mentioned, please read the document fully.
7th Jul 2020, 6:46 AM
Calviղ
Calviղ - avatar
0
You are right, Calviղ. I found out the real problem was <use> only extract the needed chunk from my sprite without reading all the other nodes in the file. That means any <style> tag used in my sprite will be ignored. All I had to do was copy and paste the CSS styles of my sprite to my global CSS. Now it works. Thanks everyone.
7th Jul 2020, 7:07 AM
Ore
Ore - avatar