Good patterns for SVG icons and images
SVG Icons - Purely decorative
Purely decorative SVG’s need the following markup to make them accessibily hidden, and non-focusable by IE and Edge:
<svg class="c-icon" aria-hidden="true" focusable="false">
<use xlink:href="/assets/icons/symbols.svg#icon"></use>
</svg>
Related
See also: Setting up SVG Icons
SVG images and graphics
External SVG within <img>
If the SVG file is linked directly via an img tag we need to add role="img".
Without the role="img" it’s not focusable in Mobile (iOS v12.1.21): Safari + VoiceOver (v12.1.2)
<img role="img" class="inline" alt="Lightbulb moment!" src="/assets/img/icon-bulb.svg">
Inline complex SVG with description
For more complex SVG’s that require built-in alternative descriptive text, the following is a good pattern, but I’d omit title as browsers will show it like a title tooltip and can drown out the description. Alternative to that is link it to a completely different ID.
<svg role="img" aria-labelledby="lightbulb11 description11" viewBox="0 0 24 24">
<title id="lightbulb11">Vue</title>
<desc id="description11">Vue.js is an open-source JavaScript framework for building user interfaces and single-page applications. And has an SVG path that is very simple for use in examples.</desc>
<path d="M19.197 1.608l.003-.006h-4.425L12 6.4v.002l-2.772-4.8H4.803v.005H0l12 20.786L24 1.608"/>
</svg>
Optimisation & compression, eg, do I need xmlns?
All user agents (browsers) ignore the version attribute, so you can always drop that.
If you embed your SVG inline in a HTML page and serve that page as
text/htmlthen xmlns attributes are not required. Embedding SVG inline in HTML documents is a fairly recent innovation that came along as part of HTML5.If however you serve your page as image/svg+xml or application/xhtml+xml or any other MIME type that causes the user agent to use an XML parser then the xmlns attributes are required.
Robert Longson
The xmlns="http://www.w3.org/2000/svg" attribute is:
- Required for image/svg+xml files. 1
- Optional for inlined
<svg>. 2
The xmlns:xlink="http://www.w3.org/1999/xlink" attribute is:
- Required for image/svg+xml files with xlink: attributes. 1
- Optional for inlined
<svg>with xlink: attributes. 2
The version="1.1" attribute is:
- Recommended to comply with image/svg+xml files standards. 3
- Apparently ignored by every user agent. 4
- Removed in SVG 2. 5
1 Internationalized Resource Identifiers (RFC3987)
2 Since HTML5
3 Extensible Markup Language (XML) 1.0
4 Probably until the release of further major versions.
5 SVG 2, W3C Candidate Recommendation, 07 August 2018
Resources
Carie Fisher - Creating Accessible SVGs - January 10, 2019
Robert Longson (Firefox’s SVG engine) - Do you need xmlns?