By now, you probably know it’s possible to use media queries in SVG. As with media queries in HTML documents, you can use CSS to adjust layout — or in this case, things like stroke and fill — based on the width of the document view port.
With SVG documents, of course, the viewport is whatever width has been specified for the <img> tag: <img src="star.svg" width="300">
, for example. This is also true, however, of background-size
.
This is a WebKit-only phenomenon to date, and only in very recent versions. Fire up a copy of Chrome or a WebKit nightly, build r148381 or later. You can also use the Opera for Android Beta. Then come back to this page using that browser.
SVG backgrounds and background-size
In the samples below, the background image is star.svg. If you view its source, you will see its media queries. Notice that there are several widths at which we adjust the fill and stroke.
In figure 1 below, we’ve set the value of the background-size
property to 50px 50px
. As, you can see, the stars lack a stroke width, and the fill is black with a 20% opacity.
Clik here to view.

50px 50px
.If, as in figure 2, we change the background size so that it’s between 150 and 250 pixels wide — say, 120-by-120 pixels — our star gains a 10 pixel stroke width and a blue background.
Clik here to view.

50px 50px
.Two elements, one image
You may have noticed that in the examples above, I’m using images rather than iframes or some other element to create a live demo. Well that’s because I ran into an a quirk of using this technique when reusing an image. In Chrome, when you reuse an image, the computed dimensions of the SVG viewport will change when the element to which it’s attached comes in or out of the viewport.
That’s probably better shown than explained, so compare the background of the document in figure 3. Then scroll down a bit to see the document in figure 4.
175px 175px
.As you may have noticed on your way to figure 4, the background in both framed documents is now blue instead of black in Chrome or a WebKit nightly build. Slowly scroll up and down a few times to see what I mean. Even though the documents are different, the browser requests the image once. As a result, a media query event in one instance will also trigger it in the other documents on the page. Other browsers do not support media queries when the SVG document is used as a background.
175px 175px
.By the way, this is also true when you reuse an image within a document, at least in WebKit/Blink browsers. For foreground images, Presto-based Opera and Internet Explorer handle media queries and SVG viewports as you’d expect. Chrome, Safari, and Firefox instead apply the media query for the last instance of the image to all instances.