{"id":272772,"date":"2018-06-21T07:11:18","date_gmt":"2018-06-21T14:11:18","guid":{"rendered":"http:\/\/css-tricks.com\/?p=272772"},"modified":"2019-03-03T14:29:56","modified_gmt":"2019-03-03T21:29:56","slug":"using-custom-fonts-with-svg-in-an-image-tag","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/using-custom-fonts-with-svg-in-an-image-tag\/","title":{"rendered":"Using Custom Fonts With SVG in an Image Tag"},"content":{"rendered":"

When we produce a PNG image, we use an <img><\/code> tag or a CSS background, and that’s about it. It is dead simple and guaranteed to work.<\/p>\n

<\/p>\n

\"\"
PNG is way simpler to use in HTML than SVG<\/figcaption><\/figure>\n

Unfortunately, the same cannot be said for SVG, despite its many advantages. Although you’re spoiled for choices when using SVG in HTML, it really boils down to inline<\/code>, <object><\/code> and <img><\/code>, all with serious gotchas and trade-offs.<\/p>\n

Problems with inline SVG<\/h3>\n

If you’re inlining SVG, you lose the ability to use browser cache, Gzip compression between servers and browsers, and search engine image indexing (inline SVG is not considered as an image). Even though your image may not have changed one bit, they are always reloaded and this causes slower loading times for your website, a trade-off that most are not willing to tolerate.<\/p>\n

In addition, inlining SVG also causes complex dependency problems where you cannot easily insert images into HTML and have to resort to scripts (PHP or otherwise). When you have more than a few images, this becomes a huge problem when it comes to maintaining your site, because essentially you can’t use the <img><\/code> tag anymore.<\/p>\n

No doubt, there are areas where inlining SVG shines — that is, if you want your images to display quickly, without waiting for other resources to load. Apart from that, clearly, you just can’t inline everything.<\/p>\n

Problems with object tag<\/h3>\n

SVG is well known for its excellent quality when displayed on devices of all resolutions and its ability to refer to external resources — like CSS and fonts — while keeping the file size very small. The idea is to have many SVGs that all share a single CSS or a single font file, to reduce the amount of resources you have to download.<\/p>\n

The myth of resource sharing<\/h4>\n

Unknown to many, sharing external resources for SVG only applies to inline SVG. Because usage of <object><\/code> tags allow access to these resources, the perception is that the browser will download a single copy of your CSS, even though you have many <object><\/code> tags referring to the same CSS file.<\/p>\n

This however, is not true at all:<\/p>\n

\"\"
Multiple object tags will download multiple CSS<\/figcaption><\/figure>\n

Compounding the problem is the fact that <object><\/code> tags are not recognized as an image, and therefore image search indexing is not possible.<\/p>\n

Further compounding the problem are dependency issues. For example, let\u2019s say you have 100 images, and 25 of them use a Roboto font, another 25 use Lato, 25 use Open Sans, while the rest use a combination of the three fonts. Your CSS would need to refer to all three fonts because it is quite impossible to keep track of which file is using which fonts, meaning you may be loading fonts you may not require on certain pages.<\/p>\n

The image tag<\/h3>\n

That leaves us with the <img><\/code> tag, which has a lot going for it. Because it’s the same tag used for other image formats, you get familiarity, browser caching, Gzip compression and image search. Each image is self-contained, with no dependency issues.<\/p>\n

\"\"
SVG losing fonts if used with the <img><\/code> tag<\/figcaption><\/figure>\n

The only problem is you will lose your fonts<\/strong>. To be more precise, if you have any text in your SVG, unless you embed fonts, your text will be displayed with system fonts, typically Times New Roman. You’ve spent hours selecting a beautiful font but the moment you use the <img><\/code> tag to embed SVG, all that is lost. How can this be acceptable?<\/p>\n

Investigating font rasterization<\/h3>\n
\"\"
Converting fonts into paths<\/figcaption><\/figure>\n

Our first reaction is to see if we can perform font rasterization. It is a commonly used technique to convert fonts into paths, so it’ll render well on all devices and maintain zero dependencies. On the surface, this works very well, and on the editor, everything looks perfect.<\/p>\n

Although the rasterized SVG came in at a whopping 137 KB<\/strong> compared to 15.7 KB<\/strong> before rasterization, we were optimistic because, after optimizing our SVG using Gzip compression, the rasterized file is reduced to 11 KB<\/strong>, slightly smaller than the equivalent PNG at 11.9 KB<\/strong>.<\/p>\n\n\n\n\n\n
Original<\/th>\nFont rasterization<\/th>\nFont rasterization (.svgz)<\/th>\n<\/tr>\n<\/thead>\n
15.7 KB<\/td>\n137 KB<\/td>\n11.0 KB<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n\n\n\n\n\n
PNG @ 1x<\/th>\nPNG @ 2x<\/th>\nPNG @ 3x<\/th>\n<\/tr>\n<\/thead>\n
11.9 KB<\/td>\n26.5 KB<\/td>\n42.6 KB<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n
\"\"
SVG image with font rasterization<\/figcaption><\/figure>\n

Alas, once we embed the rasterized SVG into HTML, we found our optimism to be premature. Although it might look great on high-resolution displays, the quality on low-resolution displays is unacceptable.<\/p>\n

\"\"
Rasterized fonts on top and original at the bottom<\/figcaption><\/figure>\n

The bottom of the image is the original, with clearly displayed fonts while, on top, fonts are pixelated with font rasterization.<\/p>\n

\"\"
Cleartype difference when shown on screens<\/figcaption><\/figure>\n

What’s happening is that most operating systems will optimize fonts to ensure they are shown clearly and sharp on all screens. On Windows, this is called ClearType<\/a>, and since we rasterized our fonts, no optimizations will be applied, resulting in blurred text, particularly visible on low-resolution screens.<\/p>\n

Obviously, a reduction in quality is unacceptable, so back to the drawing board.<\/p>\n

Font embedding to the rescue<\/h3>\n

Initially, we were extremely skeptical about font embedding, mainly because of the complicated workflow.<\/p>\n

To embed fonts in SVG, you first have to know what font families are used. Then you need to find these font files and download them. Once downloaded, you have to convert regular, bold, italics and bold italics to Base64 encoding. If you’re doing it manually, it is quite impossible, over a large number of files, to know which file uses bold and which ones does not. Then you have to copy all four Base64 encoded strings into your SVG.<\/p>\n

\"\"<\/figure>\n

Surely, there has to be a better way.<\/strong> And that\u2019s why we built Nano<\/a>. Nano scans SVG automatically and inserts only the fonts that are used. For example, if bold is not used or if no text exists, then no fonts will be embedded.<\/p>\n

Still, the resulting file is huge and is not competitive with the PNG equivalent, so we plugged away and built our own SVG optimizer (Nano) that will reduce SVG file sizes to a trickle. (See how Nano compresses SVG.<\/a>) In addition, we also optimized how we embed fonts into SVG, resulting in very small file sizes.<\/p>\n

\"\"
SVG image with text, optimized with Nano and fonts embedded<\/figcaption><\/figure>\n

Comparing file sizes and bandwidth savings<\/h3>\n\n\n\n\n\n\n
<\/th>\nOriginal<\/th>\nFont rasterization<\/th>\nUnoptimized font embedding<\/th>\nNano font embedding<\/th>\n<\/tr>\n<\/thead>\n
Size<\/td>\n15.7 KB<\/td>\n137 KB<\/td>\n65.2 KB<\/td>\n22.0 KB<\/td>\n<\/tr>\n
Gzip<\/td>\n3.57 KB<\/td>\n11.0 KB<\/td>\n44.5 KB<\/td>\n11.7 KB<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n\n\n\n\n\n\n
<\/th>\nPNG @ 1x<\/th>\nPNG @ 2x<\/th>\nPNG @ 3x<\/th>\n<\/tr>\n<\/thead>\n
Size<\/td>\n11.9 KB<\/td>\n26.5 KB<\/td>\n42.6 KB<\/td>\n<\/tr>\n
Gzip<\/td>\n12.1 KB<\/td>\n26.1 KB<\/td>\n41.7 KB<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n

From the above, we can see that Nano produces an SVG that is extremely lightweight even with embedded fonts, coming in at 11.7 KB<\/strong> (Gzipped) compared with the equivalent PNG @1x at 11.9 KB<\/strong>. While this may seem insignificant, the total bandwidth saved on your site will surely be significant.<\/p>\n

Let\u2019s assume that 50% of your traffic is low resolution, 40% is 2X resolution and the remaining 10% is 3X resolution. If your website has 10,000 hits on a single image:<\/p>\n

(5,000 * 11.9 KB) + (4,000 * 26.5 KB) + (1,000 * 42.6 KB) = 208.1 MB<\/code><\/p>\n

If you use Nano, compressed SVG with GZip:<\/p>\n

10,000 * 11.7 KB = 117.0 MB<\/code><\/p>\n

This will result in: 208.1 MB – 117.0 MB = 91.1 MB<\/code> savings, or 43.7%, bandwidth savings, a significant amount by any measure.<\/p>\n

In addition to the bandwidth savings, you get a far simpler workflow without resorting to multiple PNG images with multiple srcset<\/code>, with much better quality, including operating system font enhancement to ensure your images stay crisp and sharp on devices of all resolutions. Best of all, better user experience for your users, since your site will load faster — especially so on devices with high resolution.<\/p>\n

Thoroughly testing Nano<\/h3>\n

Not satisfied with all the savings, we began to look for SVG images to thoroughly test Nano. A total 2,571<\/strong> SVG files of various sizes and designs were used, totaling up 16.3 MB<\/code>. And after Nano optimization, resulting in 6.2 MB<\/code>, an astonishing 61.8% savings in size.<\/p>\n

\"\"
A small selection of over 2500 SVG images used to test Nano<\/figcaption><\/figure>\n

Showing a visual difference<\/h3>\n

Because of the sheer number of files that we were testing, and it increases from time to time, we have to build an automated test, including automatically highlighting pixel differences before and after optimization. One of the complaints on other SVG optimizers is the fact that minifying SVG may break your image, causing it to render differently compared to the original.<\/p>\n

To this end, we carry over the pixel differentiation in our automated test into Nano itself. That is, Nano will warn you if it detects that the SVG it optimizes has a pixel difference of more than 1% when compared to the original, therefore ensuring Nano’s optimization will never break an SVG.<\/p>\n

\"\"
Nano optimization showing visual difference<\/figcaption><\/figure>\n

Because fonts are embedded and preserved, plus SVG being a vector graphics format, rendering quality on all resolution is incomparable to other raster formats.<\/p>\n

What’s next?<\/h3>\n

We hope our work will make SVG easier to use everywhere. We’re now working on producing even smaller file sizes, porting our codes to work on Node.js so you can automate your production builds with Nano, among others.<\/p>\n

Do you think you\u2019ll find Nano helpful in your projects? Let me know in the comments!<\/p>\n","protected":false},"excerpt":{"rendered":"

When we produce a PNG image, we use an <img \/> tag or a CSS background, and that’s about it. It is dead simple and guaranteed to work.<\/p>\n","protected":false},"author":253327,"featured_media":272803,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_bbp_topic_count":0,"_bbp_reply_count":0,"_bbp_total_topic_count":0,"_bbp_total_reply_count":0,"_bbp_voice_count":0,"_bbp_anonymous_reply_count":0,"_bbp_topic_count_hidden":0,"_bbp_reply_count_hidden":0,"_bbp_forum_subforum_count":0,"sig_custom_text":"","sig_image_type":"featured-image","sig_custom_image":0,"sig_is_disabled":false,"inline_featured_image":false,"c2c_always_allow_admin_comments":false,"footnotes":"","jetpack_publicize_message":"Nano is a tool that will embed fonts into an SVG when its being used in an tag.","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":[]},"categories":[4],"tags":[712,592,469],"jetpack_publicize_connections":[],"acf":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/css-tricks.com\/wp-content\/uploads\/2018\/06\/nano-svg.png?fit=1200%2C600&ssl=1","jetpack-related-posts":[{"id":168417,"url":"https:\/\/css-tricks.com\/icon-fonts-vs-svg\/","url_meta":{"origin":272772,"position":0},"title":"Inline SVG vs Icon Fonts [CAGEMATCH]","date":"April 22, 2014","format":false,"excerpt":"If you're building an icon system for a site, you have some options. If you know the icons need to be raster images, then you'll likely be using CSS sprites. If the icons will be vector images (much more common these days), you have some options. Two of those options\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":199370,"url":"https:\/\/css-tricks.com\/a-complete-guide-to-svg-fallbacks\/","url_meta":{"origin":272772,"position":1},"title":"A Complete Guide to SVG Fallbacks","date":"May 4, 2015","format":false,"excerpt":"If you're using SVG and are worried about unsupported environments, this is the guide for you. There is no single solution, since how you use SVG dictates the fallback.","rel":"","context":"In "Article"","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/css-tricks.com\/wp-content\/uploads\/2015\/05\/svg-fallback-guide.png?fit=1200%2C600&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":147254,"url":"https:\/\/css-tricks.com\/svg-fallbacks\/","url_meta":{"origin":272772,"position":2},"title":"SVG Fallbacks","date":"August 19, 2013","format":false,"excerpt":"UPDATE: Here's a more comprehensive guide to SVG fallbacks we've published. There is a very clever technique by Alexey Ten on providing an image fallback for SVG going around the internet recently. It does just what you want in the classic no-SVG-support browsers IE 8- and Android 2.3. If we\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":175074,"url":"https:\/\/css-tricks.com\/mega-list-svg-information\/","url_meta":{"origin":272772,"position":3},"title":"A Compendium of SVG Information","date":"July 22, 2014","format":false,"excerpt":"A huge pile of information about SVG. How to Use SVG These are overview articles covering lots of stuff relating to SVG. Why to use it and the basics of how to use it. Mostly: , background-image, , , and \/. Using SVG by me SVG on the Web \u2014\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":195363,"url":"https:\/\/css-tricks.com\/inline-svg-grunticon-fallback\/","url_meta":{"origin":272772,"position":4},"title":"Inline SVG with Grunticon Fallback","date":"February 9, 2015","format":false,"excerpt":"In which we look at Grunticon and how it can be used as the fallback system even if you want to start with inline SVG in the document.","rel":"","context":"In "Article"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":171038,"url":"https:\/\/css-tricks.com\/svg-text-typographic-designs\/","url_meta":{"origin":272772,"position":5},"title":"SVG `text` and Small, Scalable, Accessible Typographic Designs","date":"May 27, 2014","format":false,"excerpt":"Let's say you designed something with custom fonts that was a little bit fancy. Perhaps a certain word is positioned between the ascenders of another word below it. Some text is kerned out below to match the width of that same word. This is something we might tell a graphic\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"featured_media_src_url":"https:\/\/i0.wp.com\/css-tricks.com\/wp-content\/uploads\/2018\/06\/nano-svg.png?fit=1024%2C512&ssl=1","_links":{"self":[{"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/posts\/272772"}],"collection":[{"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/users\/253327"}],"replies":[{"embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/comments?post=272772"}],"version-history":[{"count":26,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/posts\/272772\/revisions"}],"predecessor-version":[{"id":284036,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/posts\/272772\/revisions\/284036"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/media\/272803"}],"wp:attachment":[{"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/media?parent=272772"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/categories?post=272772"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/tags?post=272772"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}