10 golden rules for responsive SVGs (2024)

10 golden rules for responsive SVGs (1)

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

10 golden rules for responsive SVGs (2)

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 10 golden rules for responsive SVGs (3). 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

10 golden rules for responsive SVGs (4)

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

10 golden rules for responsive SVGs (5)

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 thetag:

<image width="1024" height="768" xlink:href="lake-louise.jpg" x="1300" y="150" role="image" title="Crowsnest Pass"></image>

09. Consider adaptive solutions

10 golden rules for responsive SVGs (6)

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

10 golden rules for responsive SVGs (7)

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

10 golden rules for responsive SVGs (8)

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
10 golden rules for responsive SVGs (2024)

FAQs

How to make an SVG image responsive? ›

10 golden rules for responsive SVGs
  1. Set up your tools correctly. ...
  2. Remove height and width attributes. ...
  3. Optimise and minify SVG output. ...
  4. Modify code for IE. ...
  5. Consider SVG for hero text. ...
  6. Leave width and height in place for progressive icons. ...
  7. Use vector-effects to keep hairlines thin. ...
  8. Remember bitmaps.
Mar 22, 2021

What are the best practices for SVG? ›

To optimize SVG for better performance, you can follow a few best practices. These include using vector tools to create simpler shapes, removing unnecessary elements and attributes, compressing the SVG file, and utilizing CSS to style the graphics instead of inline styles.

What does responsive mean SVG? ›

SVG's exported from Illustrator CC are 'responsive' by default, in other words there is no height or width attributes, no dimensions. This can be great, but sometimes you may want to force dimensions. Say for example you want to use an SVG for a logo on your website, but you want it to be a set size.

How to make SVG responsive in React? ›

Making SVG Images Responsive in React

In React, you can make an SVG image responsive by controlling its width and height using CSS. To make an SVG image responsive, you first need to ensure that the SVG has a viewBox attribute.

What is the most appropriate way to make SVG picture accessible? ›

The <desc> tag

The <desc> element appears after the <title> element. By default, the content in the <desc> tag is not displayed visually. Browser support for the <desc> tag has been increasing, and is currently at about 93%. To ensure that the SVG has an accessible description, WAI-ARIA attributes can be added.

What is the main competitor to SVG? ›

EPS (Encapsulated PostScript) is the standard vector file format for the print industry.

When should you not use SVG files? ›

If you're working with simple graphics, icons, or logos, SVG may be the better choice due to its smaller file sizes and ability to be scaled without losing quality. However, if you're dealing with complex images or photographs, a PNG may be more appropriate due to its lossless compression and support for transparency.

What does C mean in SVG? ›

H = horizontal lineto (create a horizontal line) V = vertical lineto (create a vertical line) C = curveto (create a curve) S = smooth curveto (create a smooth curve)

What is the best size for SVG icons? ›

Tip: Check the size on disk after saving an SVG icon

Normally it's 200-800 bytes for icons. However, some software includes a lot of redundant information, resulting in icon file sizes of 2-3 KB or more. If this is the case, try either: Playing with the presets of the software.

What are SVG ideal for? ›

As mentioned, the SVG format is best suited for images with minimal detail, since a vector graphic is a collection of shapes put together. If you're working with very detailed images, like photographs or highly detailed illustrations, raster formats are optimal.

What is path in SVG? ›

The <path> element is the most powerful element in the SVG library of basic shapes. It can be used to create lines, curves, arcs, and more. Paths create complex shapes by combining multiple straight lines or curved lines. Complex shapes composed only of straight lines can be created as <polyline> elements.

How do I make an SVG image clickable? ›

The simplest way to make a portion of an SVG clickable is to add an SVG hyperlink element to the markup. This is as easy as wrapping the target with an <a> tag, just as you would a nested html element. Your <a> tag can surround a simple shape or more complex paths. It can surround a group of SVG elements or just one.

How to resize a SVG component? ›

If you want the SVG to appear larger / smaller, adjust the viewBox width and height values. If you want the SVG position within the viewport to change, adjust the min-x and min-y values of viewBox.

How do I animate an SVG file? ›

SVGs can be animated the same way that HTML elements can, using CSS keyframes and animation properties or using CSS transitions. More complex animations usually have some kind of transformation applied — a translation, rotation, scaling, or skewing.

How do you handle SVG images? ›

SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document.

Top Articles
Elizabeth Holmes has gone to prison. Will she ever pay victims too?
Retirement Options for 1099 Employees
Ron Martin Realty Cam
Section 4Rs Dodger Stadium
Toyota Campers For Sale Craigslist
Mychart Mercy Lutherville
Math Playground Protractor
Retro Ride Teardrop
Dr Klabzuba Okc
His Lost Lycan Luna Chapter 5
Space Engineers Projector Orientation
Phillies Espn Schedule
Turbocharged Cars
Craigslist Pets Southern Md
2024 Non-Homestead Millage - Clarkston Community Schools
Craigslist Pikeville Tn
Local Dog Boarding Kennels Near Me
This Modern World Daily Kos
Cyndaquil Gen 4 Learnset
Erica Banks Net Worth | Boyfriend
Account Suspended
Icivics The Electoral Process Answer Key
Today Was A Good Day With Lyrics
Yog-Sothoth
Lexus Credit Card Login
Klsports Complex Belmont Photos
Craigslist Hunting Land For Lease In Ga
Wrights Camper & Auto Sales Llc
Cylinder Head Bolt Torque Values
Warn Notice Va
Advance Auto Parts Stock Price | AAP Stock Quote, News, and History | Markets Insider
Chicago Pd Rotten Tomatoes
Frommer's Belgium, Holland and Luxembourg (Frommer's Complete Guides) - PDF Free Download
How To Make Infinity On Calculator
Sitting Human Silhouette Demonologist
#scandalous stars | astrognossienne
Great Clips On Alameda
Ducky Mcshweeney's Reviews
The Bold And The Beautiful Recaps Soap Central
Pp503063
Td Ameritrade Learning Center
Pokemon Reborn Locations
Busch Gardens Wait Times
Sabrina Scharf Net Worth
Craigslist En Brownsville Texas
Firestone Batteries Prices
11 Best Hotels in Cologne (Köln), Germany in 2024 - My Germany Vacation
Citymd West 146Th Urgent Care - Nyc Photos
Mynord
Bank Of America Appointments Near Me
Craigslist Com Brooklyn
Latest Posts
Article information

Author: Twana Towne Ret

Last Updated:

Views: 6594

Rating: 4.3 / 5 (44 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Twana Towne Ret

Birthday: 1994-03-19

Address: Apt. 990 97439 Corwin Motorway, Port Eliseoburgh, NM 99144-2618

Phone: +5958753152963

Job: National Specialist

Hobby: Kayaking, Photography, Skydiving, Embroidery, Leather crafting, Orienteering, Cooking

Introduction: My name is Twana Towne Ret, I am a famous, talented, joyous, perfect, powerful, inquisitive, lovely person who loves writing and wants to share my knowledge and understanding with you.