Reputation: 458
I'm using a SVG spritesheet for icons. I'd like to do a color-change on :hover/:active. The only way (I've found) to change an SVG's color is if the SVG data is inline. There's a nice script to convert an external .svg into inline SVG code:
How to change color of SVG image using CSS (jQuery SVG image replacement)?
but I don't think it will work with a spritesheet, because every sprite on the page would be injected with the paths for the entire spritesheet, rather than just the 1 that particular sprite needs to display.
Is there a way to extract a specific part (sprite) of the spritesheet's xml to put into the HTML markup, based on a class (or something else)? My only thought is to manually break up the spritesheet, put each sprite path-string into an array/object, and use js (maybe Raphael) to write the inline markup and set up the hover colors; but I'm not sure what kind of overhead that would add, or if it's a really convoluted way of doing something that shouldn't be.
Upvotes: 3
Views: 4613
Reputation: 15391
One idea would be to make the spritesheet inline, give all the different sprites IDs and reference them using <svg:use>
, like so:
<html>
<head>
<title></title>
<style type="text/css">
#firstUseOfSprite1:hover{
color:green;
}
#secondUseOfSprite1:hover{
color:blue;
}
#sprite1{
fill:currentColor;
stroke:red;
stroke-width:5px;
}
#defs{
display:none;
}</style>
</head>
<body>
<!-- This is our "spritesheet" -->
<svg id="defs">
<defs>
<rect width="50" height="20" id="sprite1"/>
<circle r="20" id="sprite2"/>
</defs>
</svg>
<p>Here we use the "sprite":</p>
<div>
<svg width="55" height="25">
<use xlink:href="#sprite1" id="firstUseOfSprite1" x="2.5" y="2.5"></use>
</svg>
</div>
<p>And here, we use it again:</p>
<div>
<svg width="55" height="25">
<use xlink:href="#sprite1" id="secondUseOfSprite1" x="2.5" y="2.5"></use>
</svg>
</div>
</body>
</html>
You can even apply different hover effects for different uses of the same sprite. It seems to work fine with Firefox and Chrome, but the hover effect doesn't work with Opera for me. I didn't try IE9.
Upvotes: 2