Question

I have a SVG (a cross) which changes the color of the lines based on the hash given to the SVG url using JavaScript.

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <line x1="0" y1="0" x2="100%" y2="100%" stroke="black" stroke-width="1" />
    <line x1="100%" y1="0" x2="0" y2="100%" stroke="black" stroke-width="1" />

    <script>
        if (window.location.hash) {
            document.getElementsByTagName('line')[0].setAttribute('stroke', location.hash);
            document.getElementsByTagName('line')[1].setAttribute('stroke', location.hash);
        }
    </script>
</svg>

This works perfectly fine as an <object> element (<object type="image/svg+xml" data="img/svg/cross.svg#ff0000"></object>), but fails as an img or css background-image.

How can I make this work as a CSS background-image?

Was it helpful?

Solution 2

I have found a solution myself that works for me. I'm also using Sass, and with it I have found a base64 encode plugin. With it, I can write svg in my CSS which is then encoded to base64. And I can also use variables. The SASS code now looks like this:

background: url('data:image/svg+xml;base64,'
                + base64Encode('<svg xmlns="http://www.w3.org/2000/svg"><line x1="0" y1="0" x2="100%" y2="100%" stroke="#{$color-line}" stroke-width="1" /><line x1="100%" y1="0" x2="0" y2="100%" stroke="#{$color-line}" stroke-width="1" /></svg>'));

The base64 plugin is found here: URL- or Base64- encode strings in Compass/SASS

OTHER TIPS

Dynamic behavior in SVG that is used as an HTML image is disabled for security reasons. The reason is quite obvious - you can use an SVG image from a different domain and wouldn't really want it to run JavaScript code in the context of your document. So SVG used as an HTML image is essentially always static. There are some more details on http://www.schepers.cc/svg/blendups/embedding.html (thanks @RobertLongson for this link).

There is a work-around in Firefox: if you have inline SVG code (can be hidden) you can use a filter from that SVG code using the filter CSS property. Depending on what you are trying to achieve this can be a rather powerful tool. According to MDN Chrome and Safari should also support this but I'm not certain that they do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top