2019-02-15

Genuinely scalable SVGs with width and height attributes

It seems some software doesn't know what to do with an SVG that has no width and height attributes. These attributes have always bothered me a bit. What's so scalable about forcing your vector graphic to be a specific number of pixels or inches wide or high?

Or is it only to be taken as a hint? Firefox (65.0) doesn't think so. It fixes the image at the specified size, and treats unitless values as pixels (or maybe virtual pixels).

The desktop background under Kubuntu (18.04 as I write) does seem to take it as a hint, and a mandatory one at that. If the icon to be used for a *.desktop file is an SVG, it might display it. If you specify width and height in millimetres (say), it seems to rasterize at the size you specify, then scales the bitmap up or down as required. But if you don't specify width and height, you end up with a carefully labelled blank space on your screen.

How do you satisfy both requirements? The solution seems to be to use percentages. Check the last two fields of the viewBox attribute:

<svg viewBox='68932 -240980 190516 153908'
     ... >

Divide the smaller by the larger, and express as a percentage:

$ bc -lq
153908/190516*100
80.78481597346154653600

If the last number is smaller, use the computed value as the height; otherwise, use it as the width. Set the other attribute to 100%:

<svg viewBox='68932 -240980 190516 153908'
     width="100%" height="80.78%"
     ... >

This seems to allow Firefox to scale according to available space, while the desktop deigns to display a decently detailed icon.

I've updated Mokvino Web to re-include width and height with these computed values. I've updated my earlier article too.

Update 2021-04-06: It now looks like you should set both width and height to 100%, for the Kubuntu desktop and for Firefox at least. Bloody hell. More investigation…

No comments:

Post a Comment