Adding SVG to CSS or HTML
I recently experienced difficulties implement SVG into CSS in a cross-browser (IE 9 - Edge) manner. Outlined here are the two working solutions intended for use in production. I hope you find the learning useful too.
Both methods allow the CSS to define width, height etc. Method one is embedding raw SVGs directly into the CSS and the second using HTML embedded definition symbols.
I'll be using the Twitter logo as an example. The cleaned and compressed SVG code looks like this:
I'm not delving into cleaning an compression methods but if you want to compare against the original it may be found here: uncompressed Twitter logo.
That looks like this as a CSS background-image: and this as HTML SVG: which should appear identical in all browsers.
Raw SVG used as CSS background-image
With minor modification any raw SVG may be used in an external style sheet.
Works in all modern browsers, well those which support SVG, but Internet Explorer is quite awkward and requires:
- Replace all double quotes with single quotes:
- URI encode the hash tag:
- URI encode less-than symbol:
- URI encode greater-than symbol:
- Precede with the image type and declare the character set:
I've created a tool to convert raw SVGs to CSS background-images maybe give it a spin and let me know if it works for you?
HTML inlined SVG solution
To prevent repeating inlined SVG data use a definition symbol at the page top:
Then re-use wherever required in the HTML:
Currently trying to move symbol definitions into an external file. Which may prove to have its own issues and limitations (Internet Explorer bless). Though I believe, given a few years, externalised SVG definition files will overtake the use of SVGs in CSS background-images.
The current solution is svg4everybody which injects the definitions via an AJAX call into unsupporting browsers only. Not had time to investigate as yet but will keep this article updated.
HTML embedded SVG do not require
xmlns='http://www.w3.org/2000/svg' as it's predefined when using the HTML 5 doctype.
Symbol definitions need to be placed before usage in a some browsers, so always place at the top.
Embedding SVGs into the CSS is the currently preferred method because: it remains editable, has a smaller footprint, offers better gzip compression, and is cacheable.
Always compress SVGs before running in production. Remove all the nasty Illustrator code, simplify the structure and reduce the decimal places used. I use SVG Optimiser which is a little basic but it meets requirement.
Began using SVGOMG a lot for compression, still buggy, but a far nicer GUI.
Personally I've started coding all SVGs using single quotes to ease any transition between HTML and CSS.