8 ms·
You can achieve something like that by setting the color of the containing element and then referring to currentColor within the styles for the SVG. If you use
by Chris_Newton 10y ago
You can achieve something like that by setting the color of the containing element and then referring to currentColor within the styles for the SVG. If you use :hover and friends to change the color of the containing element, this does mean you can have the SVG change things like text or fill colours accordingly.
This technique is quite limited, though, as unfortunately it only allows passing of a single colour as a “parameter” to the SVG. In some cases, currentColor is redundant, as often if you just draw something in the SVG without specifying any colour explicitly, it will inherit the colour by default anyway.
Beyond that, you’re probably into scripting the SVG and all the vaguely-documented, non-portable, security-nightmarish possibilities that offers. For example, suppose you embed an SVG in your HTML like this:
<!DOCTYPE html>
<html>
<head>
<title>SVG Test</title>
</head>
<body>
<object data="svgtest.svg" type="image/svg+xml" data-test-color="green" />
</body>
</html>
Then suppose the SVG file itself says something like this:
<svg width="200" height="100" xmlns="http://www.w3.org/2000/svg" version="1.1">
<rect x="0" y="0" width="200" height="100" rx="5" ry="5" fill="blue" />
<script type="text/javascript"><![CDATA[
console.log(window.frameElement.getAttribute("data-test-color"));
]]></script>
</svg>
In theory, this should log "green" to your console, assuming you load both the HTML and SVG from compatible origins. This is because window.frameElement should refer to the <object> element and thus should allow access to its attributes, containing HTML document, and so on. (Note that this only works with embedding; using <img> to load the SVG should block the scripting.)
In practice, having just tried it in Chrome, Firefox and IE11, and loading from both a local disk and over HTTP, Firefox works in both cases, Chrome works over HTTP but blocks locally, and IE11 blocks in both cases (with window.frameElement being set to null in the blocked cases here). So sadly although this might be quite a useful technique if you can control your environment, it’s definitely not portable to all major browsers.