Tips for Using SVG in Mobile Websites

A few months ago I designed and helped build a mobile website. A goal of mine was to create a fast loading, resolution independent interface. SVG has been around for over 10 years, but using it is still quirky. For example, Google decided to save 1MB by excluding SVG support from Gingerbread, and that has proven to be a painful decision for mobile developers.

While there are more complicated workarounds, I tried to make things as simple as possible. Here’s a couple tips I learned that I didn’t find elsewhere.

Scale down background images. Although you can set a SVG image multiple ways, if you set it as a background image, the default android browser will not properly upscale the images. So make them large in your SVG file, and shrink them down in the UI. Fortunately, increasing the size of the image(s) does not increase the file size.

Some have suggested changing the SVG files internal dimensions from px to a realtive value such as ems. However, in my tests this doesn’t help with the default browser in Android, even in Jelly Bean.

Use pseudo class :after for positioning. Chances are if you’re using SVG, you want the interface to scale. Secondly, you might also be using relative units (eg em and rems) for positioning, margins, padding… Unfortunately, between mobile browsers positioning of SVG background images is not consistent. You will end up needing a more adjustable container which you may not be able to utilize the parent container for. Adding an additional container is more complicated than it needs to be. Keep it simple. For example:

.on-sale a:after {
background-image: url(/images/icon_sprite.svg);
background-position: 2.5rem -16.5rem;
background-size: 30rem;
width: 13rem;
height: 9rem;

If I tried to apply this directly to the parent element, I wouldn’t be able to set the width & height. Doing so is often required for using sprites, depending on the layout. Even though we’re saving file size by using SVG, we don’t want to slow things down by not using a sprite.

Another advantage of this is that you can control opacity of the image itself.

If you can drop Gingerbread support, then you don’t need to worry about a fallback. For this project, I created a PNG fallback of the SVG sprite. Sure it adds to the load time of Android 2.3 devices, but the file wasn’t that big and the majority of users still had a better experience than if I had forced all images to be PNGs. Since this site was built, new devices have come out with higher pixel densities. The SVG images are still crisp, as they should be. Had they been PNGs, they would start showing some jaggies.

2 thoughts on “Tips for Using SVG in Mobile Websites

Leave a Reply

Your email address will not be published. Required fields are marked *