Search code examples
csssvgfontsbase64font-face

Is it possible to use svg base64 in the css font-face?


I am very new to font icons. I have created a svg base64 by using svgo as per this guidelines, however I would like to use it in the css font-face instead of direct css background url. So that I can customize the icons by using font settings like font-size etc. Also it reduced the file size compared to original base64 truetype fonts.

Is this possible or Should I have to use truetype fonts alone for the base64 fonts with css font-face?

I have created a simple example as below

@font-face {
  font-family: 'i-icons';
  src: url("data:image/svg+xml;charset=utf-8;base64,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 48 48'%3E%3Cpath fill='%23000' d='M22.002 10c-.543 0-1.012.2-1.407.593A1.918 1.918 0 0 0 20 12.002v7.997H12a1.92 1.92 0 0 0-1.408.596 1.929 1.929 0 0 0-.591 1.404v4.002c0 .54.198 1.008.591 1.405.396.397.866.595 1.408.595H20V36c0 .543.197 1.011.595 1.407.395.398.864.596 1.407.596h3.999c.54 0 1.01-.198 1.405-.596.397-.396.594-.864.594-1.407v-8h8.003c.538 0 1.008-.197 1.405-.594.395-.397.594-.865.594-1.405v-4.002c0-.54-.199-1.008-.594-1.404a1.924 1.924 0 0 0-1.405-.596H28v-7.997c0-.545-.197-1.013-.594-1.409a1.933 1.933 0 0 0-1.405-.592zm2-10c4.354 0 8.366 1.072 12.045 3.219 3.678 2.143 6.59 5.056 8.737 8.734C46.926 15.63 48 19.647 48 24.002c0 4.354-1.074 8.368-3.216 12.045-2.146 3.678-5.06 6.59-8.737 8.737C32.368 46.928 28.357 48 24 48c-4.354 0-8.37-1.072-12.048-3.216-3.678-2.146-6.59-5.06-8.733-8.737C1.074 32.37 0 28.356 0 24.002c0-4.355 1.074-8.372 3.22-12.049 2.142-3.678 5.055-6.59 8.733-8.734C15.632 1.072 19.647 0 24.001 0z'/%3E%3C/svg%3E") format('svg');
  font-weight: normal;
  font-style: normal;
}

[class^="i-"], [class*=" i-"] {
  font-family: 'i-icons' !important;
  speak: none;
  font-size: 60px;
  font-style: normal;
  font-weight: normal;
}

.i-test::before {
  content: '\ea01'
}
<div class="i-test">

</div>


Solution

  • There are several things that won't work here:

    • The data url claims to be base64-encoded, but it isn't. That is actually what the article you linked is about. The url must start with data:image/svg+xml;charset=utf-8, - leave out the ;base64.
    • SVGO removes the id attributes from the content elements inside the file it claims to "optimize". That means that you can only address the SVG as a whole, but not individual content, because it cannot be identified. (For your example file, admittedly, this is a moot point, as it only contains one element.)
    • While there is a thing called SVG font, no browser implements it. It is actually deprecated.

    I'd recomend to read Sara Soueidan's overview of SVG sprites as an introduction to a better technique.