The many advantages of SVG – including infinitely scalable vector images, small file sizes and direct integration with the DOM – make it anatural fit for responsive web design. Despite the SVG specification being a decade old, its relatively recent support in many browsers and tools means there arestill a number of tricks, loopholes and gotchas that catch out even experienced web designers and developers.
Here, I've summarised the most important of these as 10 golden rules, but for more web design tools see our roundup of web hosting services and the top website builder around.
Just as a craftsman sharpens his tools before beginning work, anyone working with SVG must set their applications up to deliver vector format in the most efficient and optimised method possible. There are a number of settings to implement.
First, unless there are compelling reasons to do otherwise,set measurements to 'pixels' in your vector tool. While it doesn't matter to SVG (which will measure the viewBox and elements happily in almost any measurement system) it makes sense to develop the SVG drawing using common CSS units, rather than the print default of inches; and it also makes it much easier to add @media queries and other interventions later.
Don't make the canvas area any larger than it needs to be. Like bitmap images, any 'blank space' inthe SVG won't be used, and is best substituted withCSS margins. Note that many vector tools, suchas Sketch, will automatically 'crop' the canvas area to selected elements.
At the same time,don't crop the canvas area to the exact edges of elements. Antialiasing will still be applied to the SVG, and cutting it too close may also crop out the antialiasing. Instead, leave at least 2px clear wherever the edge of the canvas comes close toan element.
Responsiveness and performance are closely related, so set the decimal precision to be no more than two points. SVG doesn't think in integers, so a vector point can have a value of1.45882721px. This extreme precision is entirely unnecessary, and only adds to code bloat and file size, so it's better totruncate it at this point.
Get the Creative Bloq Newsletter
Daily design news, reviews, how-tos and more, as picked by the editors.
Similarly, draw vector shapes using as few points as possible. Many new designers assume more points is better, when the reverse is actually true: a few points, placed well, provide greater control over anelement, while also reducing file size.
If you're given vector files that do not follow this rule, don't worry – most vector art applications have a 'simplify' option you can use to reduce the number of points in an element without changing its shape. Alternatively, for detailed work I'd suggest aplugin like Astute Graphics' VectorScribe.
02. Remove height and width attributes
Most apps add alotof proprietary, unnecessary code in their SVG export. The onlyrequiredcode at the start of most SVG files is the following:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500"> <!-- SVG code here --></svg>
For our purposes, the most important aspect is the removal of the widthandheight attributes that most applications include automatically. This makes the SVG fully responsive in modern browsers.
If you're processing a lot of SVGs, or are in a rush, you don't need to complete this step by hand. Instead, you can follow the suggestions laid out in the third golden rule...
03. Optimise and minify SVG output
Whatever tool you use to create your SVG content, it'sstill worthwhile processing its output through a tool like SVGOMG, which will trim the code markedly. Typically, you can save around 20 to 80 per cent in file size. The same code can be integrated locally as a gulp or Grunt task.
04. Modify code for IE
Rule 2 mentioned that correctly optimised SVGs are fully responsive in modern browsers. That's true if we count Microsoft Edge as a modern browser. For IE 9-11, we have a few issues to address. If we are using the SVG as animage:
<img src="countdown.svg alt="Countdown">
We can force IE9-11 to display the image correctly using the CSS attribute selector:
img[src$=".svg"] {width: 100%;}
SVG images work well in general production, but have limited interactivity: most browsers will ignore interactivity and animation inside an SVG placed on a page as an . In addition, SVG images are an extra HTTP request for the browser.
For these and other reasons, SVG is increasingly used inline. In that case, the SVG code needs a little more treatment for IE:
<body>…<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 525 365" preserveAspectRatio="xMidYMin slice">
In addition to thepreserveAspectRatioattribute, IEneeds a little more guidance to preserve the correct scaling of the image: take thewidthof theSVG (365in this case), divide it by the height (525) and multiply the result by 100 per cent. Thiswill become thepadding-bottomvalue for the SVG, 'propping' it open enough in IE to display theSVG in itscorrect aspect ratio:
<body>…<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 525 365" preserveAspectRatio="xMidYMin slice"style="width: 100%; padding-bottom: 69.52%; height: 1px; overflow: visible">
Note that, in order to keep things concise and clear, the code samples in the rest of this article don't include these changes. Amelia Bellamy-Royds has written anexcellent article on scaling SVG.
05. Consider SVG for hero text
There's currently no CSS standard for sizing text to its container. It's possible to scale text using vwunits, but that will almost always require at leasttwo media query interventions to 'clamp' thetext at certain viewport limits. However, SVG textwillresize to a container automatically:
<header> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 285 80"> <text x="0" y="66">Kauai</text></svg></header>
The CSS:
header svg text {font-weight: 900; font-size: 90px; fill: blue;}
Keeping the SVG inline preserves accessibility and SEO value,andallows the text to be styled using any font already embedded in the page. See for more information.
06. Leave width and height in place for progressive icons
One exception to Rule 2 is icons and small logos, which should retain their width and height attributes if you want them to be progressively enhanced:
<a href="http://codepen.io"> <svg role="img" aria-label="CodePen" width="50" height="50"> <title>Codepen</title> <use xlink:href="#codepen" /> </svg></a>…<svg style="display: none;"> <symbol id="codepen" viewBox="0 0 50 50"> <path d="…"/> </symbol></svg>
You can see an example of this technique in action here.
If weonlysize the SVG icons with CSS, and the site's style sheetdoesn'tload, the icons will appear atthe default size of a replaced element: 300px x 150px. By keeping the height and width as attributes, we can size them to the nearest reasonable touch sizeby default, and use our CSS toenhancetheway they are presented.
07. Use vector-effects to keep hairlines thin
By default, SVG scaleseverythingwith the viewport, including stroke thickness. Usually this works out fine, but in some cases – diagrams and strokes applied as effects on the outside of text in particular – you may want to keep strokes the same thickness, no matter what the size of the drawing. This is the domain of the little-knownvector-effectproperty, which can be applied as a presentation attribute orinCSS:
path { fill: #fff; stroke: #111; stroke-width: 2; vector-effect: non-scaling-stroke;}
Take a look at a full example of this technique.
08. Remember bitmaps
Many developers assume SVG can only use vectors, but JPEGs and PNGs can also be applied to an SVG drawing. And so long as you've followed my rules sofar, those images will be responsive when you adda bitmap via the
<image width="1024" height="768" xlink:href="lake-louise.jpg" x="1300" y="150" role="image" title="Crowsnest Pass"></image>
09. Consider adaptive solutions
Making things go 'squish' is only one part of responsive design. What RWD is about, in the larger sense of adaptive design, is presenting appropriate content atall viewport sizes.
This can be achieved in a variety of ways. responsivelogos.co.uk provides a series of examples that use SVG sprites, but I prefer to integrate media queries into the SVG to create what I call 'branding modules'. This approach enables me to add, remove and modify the visibility of components. Read more about adaptive branding modules in my article.
This same technique can be used for diagrams, illustrations, maps and more. In the simplest modules, the CSS itself can be written inside the SVG, making it usable everywhere, as outlined in theprevious rule.
Many people don't know that CSS media queries can be written inside SVG itself:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="14 82 272 139"><defs><style>svg g { transition: 1s; }@media all and (max-width: 90rem) {#drink, #co*ke { opacity: 0; }}</style></defs><g id="coca-cola"><path d="M109.6… >
It's important to note that the media query can only 'see' the element it is inside of: that is, any measurement relates to the element itself, not thepage. One potential downside of this approach isthat the canvas area of the SVG will always remain the same, relative to the elements inside it.
This can result in very small elements at small viewport sizes, framed inside a relatively large canvas area. There are several solutions to this, including resizing the viewBox and scaling up the elements to compensate.
Conclusion
The infinite scalability of SVG is its greatest asset, but a feature that is still somewhat underserved bybrowsers and vector graphics editors. By integrating these guidelines into your production workflow and communicating them to others in your team, you can create smoothly responsive SVG for the web, making it partof the assets you use in development every day. Remember, if you're embarking on a design project, be sure you've got the perfect cloud storage for your needs.
This article originally appeared in net magazine issue 283; buy it here!
Related articles:
- 12 must-have code testing tools
- Sharpen your sketching skills
- Supercharge SVG animations with GSAP
Thank you for reading 5 articles this month* Join now for unlimited access
Enjoy your first month for just £1 / $1 / €1
*Read 5 free articles per month without a subscription
Join now for unlimited access
Try first month for just £1 / $1 / €1
Dudley Storey
Dudley Storey is a developer, designer, instructor and writer.
Related articles
- The best (and worst) web design trends of 2024
- The year's biggest web design trends so far, according to Wix Studio
- Strange new Mozilla logo could be a cryptic nod to internet history
- How to make an artist website