【问题标题】:Base64 encoded OpenType font-face using data URI使用数据 URI 的 Base64 编码 OpenType 字体
【发布时间】:2016-01-31 22:17:34
【问题描述】:

我想在 font-face 中添加一个base64 encoded OpenType 字体作为数据 URI。

到目前为止我有这个:

@font-face {
    font-family: 'test';
    src: url(data:font/otf;base64,
        // Base64 string here ...
    ) format('opentype');
}

但我认为它没有将字体正确地包含在我的风格中。

对此的任何帮助将不胜感激。

【问题讨论】:

  • 请使用's 包装这些值。你用的是什么浏览器?
  • 我试过了,还有谷歌浏览器
  • 哦,是的,是font/opentype 不是otf
  • 还是不行:(

标签: html css base64 font-face


【解决方案1】:

数据 URI 始终采用以下格式:

data:[<mediatype>][;base64],<data>

每个data URI 的第一部分是media-type,在Open Type 字体的情况下是:

font/opentype

所以,你可以这样使用它:

@font-face{
    font-family: test;
    src: url(data:font/opentype; base64, [base64 string here]);
}

更换

[base64 string here]

使用您的 base-64 编码字符串的精确复制粘贴版本。

备注

请注意:

  • 您应该将font/opentype 用于data,而不是otf
  • 您应该复制粘贴确切的 base-64 编码字符串,不要进行任何更改,例如添加空格等(我相信其中有一些空格)

在线编码工具

您可以使用this 工具,将您的字体文件转换为编码字符串。

【讨论】:

  • 做“……”重要吗?
  • 只需将 // Base64 string here ... 替换为 base-64 编码字符串的复制粘贴版本
  • 所有字体都兼容base64吗?
  • 是的。 base64 与文件类型无关。它只是一种编码方法,它读取文件内容并将其编码为字符串。请仔细阅读答案,我相信你会付诸实施
  • @Pmpr 支持较低版本的 IE(如 IE8)的等价物是什么?因为 AFAIK,所以 IE10 及更高版本支持 base64。如果我错了,请纠正我
【解决方案2】:

虽然没有被问到,但我相信有人会来这里寻找 woff2 解决方案,并且会遇到与我相同的问题。使用此站点上传文件:https://base64.guru/converter/encode/file 确保使用“数据 URI”选项。将 url() 值替换为网站中的代码。

对于 CSS,我必须使用以下代码:

@font-face {
    font-family: 'MYFONT'; /*This is what your font will be named*/
    src: local('MYFONT'), /* It will check the machine for a font matching this name, if it exists it will use this. Not needed when your are writing the woff2 file since you already sending all the data. */
         url('data:@file/octet-stream;base64,d09GMgABAAAAAK6kABIAAAABgQgAAK47AAA=') /*This is the base64 code copy pasted from the site*/
         format('woff2'); /*This ensures the browser treats it as a WOFF2 file. Notice there is no comma after the url() */
}

要让您的自定义字体工作,您需要指定它:

<div style="font-family: MYFONT">
    My new font
</div>

我发布的实际 base64 代码不起作用。我使用的 woff2 文件是 50kb 并且不想要一页又一页的 base64 代码。

【讨论】:

  • 你使用 data:@file 而不是 data:font?
猜你喜欢
  • 2020-05-01
  • 1970-01-01
  • 2015-05-21
  • 2012-12-05
  • 2023-03-11
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
  • 2019-12-07
相关资源
最近更新 更多