Posts from Friday, July 21st, 2017

Adding Backgrounds to Directly Loaded SVGs

Published 6 years, 8 months past

My primary SVG viewer is Firefox.  This is partly because it’s always running, so the startup time is essentially zero.  It also allows me to directly inspect and modify elements of the SVG element through the Web Inspector, which can be handy.

But I’ve run into a problem more than once, which is that if I load an SVG file in Firefox, the browser window’s background defaults to white, and a lot of times I’m trying to view images that are partially or entirely white.  I started thinking that if there were a way to make the window background medium gray, that would solve the problem with rare downsides, since I can’t remember trying to view an all-medium-gray SVG.

After a question on Twitter and some ideas from Tibor Martini, I realized I could use Stylish to give the SVG files a background through CSS.  I didn’t want to select all SVGs, only those I was loading directly, so I tried this:

svg:root {background: gray;}

And it worked!  So I decided to make it more robust by doing a multicolor gradient, and grayscaling it on hover.  I couldn’t use filter because that would grayscale the whole image, rather than just the background, but that was easy to work around.  I ended up with this:

svg:root {background: linear-gradient(135deg, hsl(0,50%,60%), hsl(180,50%,40%));}
svg:root:hover {background: linear-gradient(135deg, hsl(0,0%,60%), hsl(180,0%,40%));}

Which works great!  Except that I discovered Firefox applies it to all SVGs, even those loaded into HTML documents via img.  SVGs apparently define their own roots, which I hadn’t expected, but I can see how it might make sense.  So I poked around in MDN until I came up with this:

@-moz-document url-prefix(file:) {
    svg:root {background: linear-gradient(135deg, hsl(0,50%,60%), hsl(180,50%,40%));}
    svg:root:hover {background: linear-gradient(135deg, hsl(0,0%,60%), hsl(180,0%,40%));}
}

And that’s exactly what I wanted.  If it’s useful to you, have at it.  Just paste that into a new Stylish rule in Firefox, and you should be good to go.

If you’re on Chrome, you can import the above into Stylish and create a new rule, but it hasn’t worked for me, and I’m not sure why not.  Removing :root didn’t fix it when I tried, and that shouldn’t matter anyway: I can see in Chrome’s user styles that svg:root is used and applied.  And my Stylish toolbar icon shows the rule is being applied.  It just doesn’t do anything I can see.  If anyone can figure out how to make it work, or explain why it can’t work, I’d love to know in the comments!


Browse the Archive