将字体嵌入到 CSS 中,但字体未显示在 html 文件中

Posted

技术标签:

【中文标题】将字体嵌入到 CSS 中,但字体未显示在 html 文件中【英文标题】:Embedding a font into CSS, but the font does not show up in html file 【发布时间】:2022-01-04 20:35:09 【问题描述】:

这里的过程有点困惑,但我尝试将新字体嵌入到 html 网站的 CSS 文件中,但无论我尝试什么,该字体都不会出现在 html 网站上。我已经将字体通过转换器,然后将整个文件放入我的 CSS 文件夹中,该文件夹与我的 index.html 位于同一文件中,但无济于事。这是我放入 CSS 中的代码:

    font-family: 'Montserrat';
    src: url('Montserrat-SemiBold.woff2') format('woff2'),
        url('Montserrat-SemiBold.woff') format('woff'),
        url('Montserrat-SemiBold.ttf') format('truetype');
    font-weight: 600;
    font-style: normal;
    font-display: swap;

有什么办法可以让代码正确显示吗?

【问题讨论】:

【参考方案1】:

从这里开始: https://www.w3schools.com/cs-s-ref/css3_pr_font-face_rule.asp

你好世界示例

您应该添加一个CSS selector(选择元素)body,例如:

<!DOCTYPE HTML>

<html>

<head>
    <style>
        @font-face 
            font-family: 'hello-font';
            font-weight: 600;
            /* Use chrome inspect and check if the path is correct */
            src: url(hello-font.woff2) format('woff2');
        
        /* missing in your styles */
        body 
            font-family: 'hello-font', sans-serif;
        
    </style>
    <title>Your Website</title>
</head>

<body>
    <h1>hello world</h1>
</body>

</html>

“找不到文件”

无论如何,如果您使用本地文件 - 无法知道路径/文件名是否正确没有实时 URL(Chrome 检查 red 错误) - 错误示例:

选项 2(更好) - 通过 CDN 加载 google 字体

** 更好的速度性能/更易于维护。

<html>
  <head>
    <link rel="stylesheet"
          href="https://fonts.googleapis.com/css?family=Tangerine">
    <style>
      body 
        font-family: 'Tangerine', serif;
        font-size: 48px;
      
    </style>
  </head>
  <body>
    <div>Making the Web Beautiful!</div>
  </body>
</html>

https://fonts.google.com/specimen/Montserrat

https://developers.google.com/fonts/docs/getting_started

https://www.w3schools.com/css/css_font_google.asp

【讨论】:

非常感谢您帮助我!我很欣赏这些选项和解释,这非常有帮助。 太棒了 :) 如果答案解决了您的问题,请将答案标记为“解决方案”。谢谢!【参考方案2】:

您应该添加@font-face 关键字来导入字体 See this example

【讨论】:

感谢输入,但是添加后,字体仍然没有出现在html文件中。 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。

以上是关于将字体嵌入到 CSS 中,但字体未显示在 html 文件中的主要内容,如果未能解决你的问题,请参考以下文章

如何在现有 PDF 中嵌入字体?

字体在 HTML 页面中未正确显示

ggplot在pdf中嵌入字体

使用 PDFBox 为扁平化 PDF 表单嵌入字体

如何使用nuxt js将字体嵌入到所有页面

如何从 C# WPF 中的嵌入字体将字体文件添加到 Stimulsoft 报告